标签:leetcode
https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
http://blog.csdn.net/linhuanmars/article/details/24390157
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null || inorder.length == 0 || postorder == null || postorder.length == 0 || inorder.length != postorder.length)
return null;
Map<Integer, Integer> inorderMap = new HashMap<>();
for (int i = 0 ; i < inorder.length ; i ++)
{
inorderMap.put(inorder[i], i);
}
return build(0, inorder.length - 1, postorder, 0, postorder.length - 1, inorderMap);
}
private TreeNode build(int inStart, int inEnd, int[] postorder, int postStart, int postEnd, Map<Integer, Integer> inorderMap)
{
if(inStart > inEnd || postStart > postEnd)
return null;
int rootValue = postorder[postEnd];
TreeNode root = new TreeNode(rootValue);
int k = inorderMap.get(rootValue);
// From the post-order array, we know that last element is the root. We can find the root in in-order array. Then we can identify the left and right sub-trees of the root from in-order array.
// !!! Using the length of left sub-tree, we can identify left and right sub-trees in post-order array. Recursively, we can build up the tree.
int rightnodes = inEnd - k; // how many nodes on the right of k;
root.right = build(k+1, inEnd, postorder, postEnd - 1 - rightnodes + 1, postEnd - 1, inorderMap);
root.left = build(inStart, k-1, postorder, postStart, postEnd - 1 - rightnodes, inorderMap);
// Becuase k is not the length, it it need to -(inStart+1) to get the length
return root;
}
}[LeetCode]106 Construct Binary Tree from Inorder and Postorder Traversal
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1599619