Question

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.


本题难度Medium。

二分法

【复杂度】
时间 O(N) 空间 O(N)

【思路】
与​​[LeetCode]Construct Binary Tree from Preorder and Inorder Traversal​​相似。后序序列的特点则是根在最后,然后在根前面的那部分中:前面部分是左子树,后面的部分是右子树。因此反过来,先建立右子树,后建立左子树。

【代码】

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int postEnd=0;
public TreeNode buildTree(int[] inorder, int[] postorder) {
postEnd=postorder.length-1;
return helper(0,inorder.length-1,inorder,postorder);
}
private TreeNode helper(int inStart,int inEnd,int[] inorder, int[] postorder){
//base case
if(inStart>inEnd)
return null;

TreeNode root=new TreeNode(postorder[postEnd--]);
int inMid=0;
for(int i=inStart;i<=inEnd;i++){
if(root.val==inorder[i]){
inMid=i;
break;
}
}
root.right=helper(inMid+1,inEnd,inorder,postorder);
root.left=helper(inStart,inMid-1,inorder,postorder);
return root;
}
}