【题目】
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
题意:根据二叉树中序遍历和后序遍历的结果,构造该二叉树。参照 根据先序遍历和中序遍历结果构造二叉树。
首先明确一下,中序遍历顺序:left - root - right,后序遍历顺序:left - right - root。
很显然,后序遍历的最后一个节点就是该二叉树的根节点。
找到根节点在中序遍历数组中的位置,那么其之前的元素都是根节点的左支树,其之后的元素都是根节点的右支数。
这样递归左右两个子数组,分别找出左右子树的根节点。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int[] inorder;
int[] postorder;
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder.length < 1 || postorder.length < 1) return null;
this.inorder = inorder;
this.postorder = postorder;
return getRoot(0, inorder.length - 1, inorder.length - 1);
}
// sub-tree ranges from begin to end in inorder[], it's root is postorder[rootpos]
public TreeNode getRoot(int begin, int end, int rootpos) {
if (begin > end) return null;
TreeNode root = new TreeNode(postorder[rootpos]);
int i;
for (i = begin; i <= end; i++) {
if (inorder[i] == postorder[rootpos]) break;
}
// left sub-tree has (i - begin) nodes, right sub-tree has (end - i) nodes
root.left = getRoot(begin, i - 1, rootpos - 1 - (end - i));
root.right = getRoot(i + 1, end, rootpos - 1);
return root;
}
}