Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
解决方法一:Runtime: 22 ms
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return tree(inorder,0,inorder.length-1,postorder,postorder.length-1);
}
private TreeNode tree(int[] inorder,int left,int right, int[] postorder, int index){
if(index<0||left>right) return null;
if(left==right){
TreeNode node = new TreeNode(inorder[left]);
node.left=null;
node.right=null;
return node;
}
for(int i=index;i>=0;i--){
for(int j=left;j<=right;j++){
if(inorder[j]==postorder[i]){
TreeNode node = new TreeNode(postorder[i]);
node.left=tree(inorder,left,j-1,postorder,index-1);
node.right=tree(inorder,j+1,right,postorder,index-1);
return node;
}
}
}
return null;
}
}
参考: