Related: LeetCode 889 - Construct Binary Tree from Preorder and Postorder Traversal
X.
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34541/5ms-Java-Clean-Solution-with-Caching
http://blog.csdn.net/linhuanmars/article/details/24389549
对于寻找根所对应的下标,我们可以先建立一个HashMap,以免后面需要进行线行搜索,这样每次递归中就只需要常量操作就可以完成对根的确定和左右子树的分割。算法最终相当于一次树的遍历,每个结点只会被访问一次,所以时间复杂度是O(n)
https://leetcode.com/articles/construct-binary-tree-from-preorder-and-inorder-tr/
X. O(N^2)
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34538/My-Accepted-Java-Solution
https://www.tianmaying.com/tutorial/LC105
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return work(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1); } // 为了避免数组的复杂操作,这里直接用左右界和数组的引用来代表一段前序遍历和中序遍历 // 即preorder[lp, rp]代表了当前子树的前序遍历,inorder[li, ri]代表了当前子树的中序遍历 TreeNode* work(vector<int>& preorder, vector<int>& inorder, int lp, int rp, int li, int ri) { // 判断长度为0的情况 if (lp > rp) return NULL; // 设置根节点 TreeNode *root = new TreeNode(preorder[lp]); // 找到根节点在inorder中的位置 for (int k = li; k <= ri; k++) { if (preorder[lp] == inorder[k]) { // 分治处理两棵子树 root -> left = work(preorder, inorder, lp + 1, lp + (k - li), li, k - 1); root -> right = work(preorder, inorder, lp + (k - li) + 1, rp, k + 1, ri); } } // 返回这棵子树 return root; }
public TreeNode buildTree(int[] preorder, int[] inorder) {
T(n)=T(l)+T(n−l−1)+O(n).
When the tree is quite balanced, the time complexity isO(n) . But in case where the tree is very unbalanced (e.g. each node except the root is the right/left child of its parent), the time complexity grows up to O(n2)
Time Complexity: O(n^2). Worst case occurs when tree is left skewed.
http://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/
X. Stack
https://blog.csdn.net/crazy1235/article/details/51559645
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34715/Share-my-iterative-java-solution
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34712/Here-is-the-iterative-solution-in-Java
http://www.cnblogs.com/grandyang/p/4296500.html
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7] inorder = [9,3,15,20,7]
Return the following binary tree:
3 / \ 9 20 / \ 15 7
X.
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34541/5ms-Java-Clean-Solution-with-Caching
In this questions, most of people just loop through
inorder[]
to find the root. However, by caching positions of inorder[]
indices using a HashMap, the run time can drop from 20ms
to 5ms
.public TreeNode buildTree(int[] preorder, int[] inorder) {
Map<Integer, Integer> inMap = new HashMap<Integer, Integer>();
for(int i = 0; i < inorder.length; i++) {
inMap.put(inorder[i], i);
}
TreeNode root = buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, inMap);
return root;
}
public TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd, Map<Integer, Integer> inMap) {
if(preStart > preEnd || inStart > inEnd) return null;
TreeNode root = new TreeNode(preorder[preStart]);
int inRoot = inMap.get(root.val);
int numsLeft = inRoot - inStart;
root.left = buildTree(preorder, preStart + 1, preStart + numsLeft, inorder, inStart, inRoot - 1, inMap);
root.right = buildTree(preorder, preStart + numsLeft + 1, preEnd, inorder, inRoot + 1, inEnd, inMap);
return root;
}
Using Hashmap to cache Inorder Positionhttp://blog.csdn.net/linhuanmars/article/details/24389549
对于寻找根所对应的下标,我们可以先建立一个HashMap,以免后面需要进行线行搜索,这样每次递归中就只需要常量操作就可以完成对根的确定和左右子树的分割。算法最终相当于一次树的遍历,每个结点只会被访问一次,所以时间复杂度是O(n)
public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder==null || inorder==null) return null; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0;i<inorder.length;i++) { map.put(inorder[i],i); } return helper(preorder,0,preorder.length-1,inorder,0,inorder.length-1, map); } private TreeNode helper(int[] preorder, int preL, int preR, int[] inorder, int inL, int inR, HashMap<Integer, Integer> map) { if(preL>preR || inL>inR) return null; TreeNode root = new TreeNode(preorder[preL]); int index = map.get(root.val); root.left = helper(preorder, preL+1, index-inL+preL, inorder, inL, index-1, map); root.right = helper(preorder, preL+index-inL+1, preR, inorder, index+1, inR,map); return root; }
Same idea with less parameter passing. Since there is no passing by reference, I'm using a single element int array to denote the current position at preorder array. Should be quite straightforward without considering inorder array's index.
public TreeNode buildTree(int[] preorder, int[] inorder) {
int[] current = {0};
TreeNode root;
Map<Integer, Integer> inMap = new HashMap<Integer, Integer>();
for(int i = 0; i < inorder.length; i++) {
inMap.put(inorder[i], i);
}
root = buildTree(preorder, current, 0, preorder.length - 1, inMap);
return root;
}
public TreeNode buildTree(int[] preorder, int[] current, int low, int high, Map<Integer, Integer> inMap){
if (current[0] >= preorder.length) return null;
TreeNode root = new TreeNode(preorder[current[0]]);
if (low > high) return null;
else {
current[0] += 1;
int i = inMap.get(root.val);
root.left = buildTree(preorder, current, low, i - 1, inMap);
root.right = buildTree(preorder, current, i + 1, high, inMap);
}
return root;
}
}
X.https://leetcode.com/articles/construct-binary-tree-from-preorder-and-inorder-tr/
- Time complexity : the popleft operation is cheap , but search by index operation in the inorder list requires up to operations and the construction of inorder lists for the left and right subtrees requires operations, where
N
is a number of nodes in the tree. For instance, for the first call of the function, the maximum cost is , for the second , and so on and so forth. Now let's compute the number of operations for the worst case of completely unbalanced tree : , therefore the time complexity is . - Space complexity : , since we store the entire tree.
public Pair<TreeNode, int[]> helper(int[] preorder, int[] inorder) {
if (inorder.length == 0) {
return new Pair(null, preorder);
}
// pick up the first element as a root
int root_val = preorder[0];
TreeNode root = new TreeNode(root_val);
// find index of root in the inorder list
int index = 0;
for (; (index < inorder.length) && (inorder[index] != root_val); index++) {
}
preorder = Arrays.copyOfRange(preorder, 1, preorder.length);
// root splits inorder list
// into left and right subtrees
int[] left_inorder = Arrays.copyOfRange(inorder, 0, index);
int[] right_inorder = index + 1 <= inorder.length ? Arrays.copyOfRange(inorder, index + 1, inorder.length)
: new int[0];
// recursion
Pair<TreeNode, int[]> p = helper(preorder, left_inorder);
root.left = p.getKey();
preorder = p.getValue();
p = helper(preorder, right_inorder);
root.right = p.getKey();
preorder = p.getValue();
return new Pair(root, preorder);
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
Pair<TreeNode, int[]> result = helper(preorder, inorder);
return result.getKey();
}
X. O(N^2)
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34538/My-Accepted-Java-Solution
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return work(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1); } // 为了避免数组的复杂操作,这里直接用左右界和数组的引用来代表一段前序遍历和中序遍历 // 即preorder[lp, rp]代表了当前子树的前序遍历,inorder[li, ri]代表了当前子树的中序遍历 TreeNode* work(vector<int>& preorder, vector<int>& inorder, int lp, int rp, int li, int ri) { // 判断长度为0的情况 if (lp > rp) return NULL; // 设置根节点 TreeNode *root = new TreeNode(preorder[lp]); // 找到根节点在inorder中的位置 for (int k = li; k <= ri; k++) { if (preorder[lp] == inorder[k]) { // 分治处理两棵子树 root -> left = work(preorder, inorder, lp + 1, lp + (k - li), li, k - 1); root -> right = work(preorder, inorder, lp + (k - li) + 1, rp, k + 1, ri); } } // 返回这棵子树 return root; }
if (preorder == null || inorder == null ||
preorder.length != inorder.length || preorder.length == 0)
return null;
return recursiveBuildTree(preorder, 0, inorder, 0, preorder.length);
}
private TreeNode recursiveBuildTree(int[] preorder, int preBegin, int[] inorder, int inBegin, int len) {
assert preBegin+len <= preorder.length;
assert inBegin+len <= inorder.length;
if (len <= 0) // Empty tree
return null;
// The beginning node in the preorder traversal is the root
TreeNode root = new TreeNode(preorder[preBegin]);
// Find the position of the root in the inorder traversal so as to decide the number of nodes
// in its left subtree
int leftTreeLen = 0;
for(; leftTreeLen < len && inorder[inBegin+leftTreeLen] != root.val; leftTreeLen++);
// Recursively build its left subtree and right subtree; note the change in preBegin, inBegin, and len
TreeNode left = recursiveBuildTree(preorder, preBegin+1, inorder, inBegin, leftTreeLen);
TreeNode right = recursiveBuildTree(preorder, preBegin+leftTreeLen+1, inorder, inBegin+leftTreeLen+1,
len-leftTreeLen-1);
// Link the left and right subtrees with the root
root.left = left;
root.right = right;
return root;
}
The running time T(n) satisfies the following relation:
When the tree is quite balanced, the time complexity is
Time Complexity: O(n^2). Worst case occurs when tree is left skewed.
http://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/
X. Stack
https://blog.csdn.net/crazy1235/article/details/51559645
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34715/Share-my-iterative-java-solution
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (inorder.length==0) return null;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode root = new TreeNode(Integer.MIN_VALUE);
stack.push(root);
int i=0, j=0;
TreeNode node = null;
TreeNode cur = root;
while (j<inorder.length){
if (stack.peek().val == inorder[j]){
node = stack.pop();
j++;
}
else if (node!=null){
cur = new TreeNode(preorder[i]);
node.right = cur;
node=null;
stack.push(cur);
i++;
}
else {
cur = new TreeNode(preorder[i]);
stack.peek().left = cur;
stack.push(cur);
i++;
}
}
return root.left;
}
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34607/Deep-Understanding-on-the-Iterative-Solution- Let's first observe the sequence of inorder traversal.
1) ####$---##$---0+++
2) 0: The root node of a tree
3) #: the left child or grandchildren of root node 0, without right child
4) $: the left child or grandchildren of root node 0, with a right child or subtree.
5) --- : represent right subtree of node $
6) +++: represent right subtree of root node. - Let's observe the sequence of preorder traveral
1) 0$##$###------+++
2) The symbols are the same. - Maintain two pointers: ptrin, ptrpre
1) ptrpre: pointer to preorder sequence, always points to the next node that is about to be created.
2) ptrin: pointer to inorder sequence. When we keep pushing into stack, ptrin always points to the deepest left child of a subtree. When we keeping popping out nodes, ptrin points to nodes that has no right child, until it points to the root of the right subtree of a node that is just popped out from the stack. - Maintain a stack
1) Similar with the stack in inorder traversal, it always stores the chain of left children in a subtree.
2) When pushing stack, we are traversing the chain of left children in a subtree, and we keeping creating new node and make it as the left child of the node at stack top.
3) When poping stack, we always pop out a node that has no right child, until we find a node that has right child (subtree). - Maintain a temp pointer, that always points to a node popped from stack, the last node that is popped out from the stack has right child (subtree). So the newly created node will be the right child of temp.
- Procedures of my algorithm:
1) Create the root node of the entire tree, record the root node for the purpose of return. Push the root node into the stack.
2) While we has remaining node to create
(a) When we enter a new iteration, ptrin always points to the deepest left grandchild of a tree. So as long as we have not reached it, we can safely keep creating new left child (grandchild) for top node at stack. This actually creating the chain of left children for a tree, namely ###$#$0. The newly-created node will be pushed in the stack. So, next created node will be its left child.
(b) Now, after the previous step, we have reached the deepest left child of a tree. Remember inorder traveral, now we need to retreat from the deepest left child until we find the first node that has a right child or subtree. We use a temp pointer to record the node that has right child, than we create the right child for it. This is achievable, because ptrpre always points to the next node that will be created. In other word, now, the node pointed by ptrpre is the right child. This invariant is ensured by the characteristics of preorder traversal. Remember the symbol presentation: 0$##$###------+++. After we create the left children chain: 0$##$###, now the ptrpre points to the first -, which is the right child of the first node with right child (the second $).
(c) Repeat step (a) and step (c) until we create all nodes.
(c) Repeat step (a) and step (c) until we create all nodes.
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.empty()) return NULL;
int ppre = 0, pin = 0;
TreeNode* root = new TreeNode(preorder[ppre++]);
stack<TreeNode*> stk;
stk.push(root);
while(true) {
while(stk.top()->val != inorder[pin]) {
TreeNode* newnode = new TreeNode(preorder[ppre++]);
stk.top()->left = newnode;
stk.push(newnode);
}
TreeNode* node;
while(!stk.empty() && stk.top()->val == inorder[pin]) {
node = stk.top();
stk.pop();
pin++;
}
if(ppre == preorder.size()) break;
TreeNode* newnode = new TreeNode(preorder[ppre++]);
node->right = newnode;
stk.push(newnode);
}
return root;
}
http://articles.leetcode.com/2011/04/construct-binary-tree-from-inorder-and-preorder-postorder-traversal.htmlhttp://www.cnblogs.com/grandyang/p/4296500.html
做完这道题后,大多人可能会有个疑问,怎么没有由先序和后序遍历建立二叉树呢,这是因为先序和后序遍历不能唯一的确定一个二叉树,比如下面五棵树:
1 preorder: 1 2 3
/ \ inorder: 2 1 3
2 3 postorder: 2 3 1
/ \ inorder: 2 1 3
2 3 postorder: 2 3 1
1 preorder: 1 2 3
/ inorder: 3 2 1
2 postorder: 3 2 1
/
3
/ inorder: 3 2 1
2 postorder: 3 2 1
/
3
1 preorder: 1 2 3
/ inorder: 2 3 1
2 postorder: 3 2 1
\
3
/ inorder: 2 3 1
2 postorder: 3 2 1
\
3
1 preorder: 1 2 3
\ inorder: 1 3 2
2 postorder: 3 2 1
/
3
\ inorder: 1 3 2
2 postorder: 3 2 1
/
3
1 preorder: 1 2 3
\ inorder: 1 2 3
2 postorder: 3 2 1
\
3
\ inorder: 1 2 3
2 postorder: 3 2 1
\
3
从上面我们可以看出,对于先序遍历都为1 2 3的五棵二叉树,它们的中序遍历都不相同,而它们的后序遍历却有相同的,所以只有和中序遍历一起才能唯一的确定一棵二叉树。