这两题主要是用找规律的方法,找出两种序列的关系然后递归构造即可。
public class Solution {
private TreeNode generate(int i, int j, int m, int n, int[] preorder, int[] inorder){
if(i==j)
return new TreeNode(preorder[i]);
if(i>j)
return null;
TreeNode root = new TreeNode(preorder[i]);
int r;
for(r=m;r<=n;r++){
if(inorder[r]==preorder[i]){
root.left=generate(i+1,i+r-m,m,r-1,preorder,inorder);
break;
}
}
root.right=generate(i+r-m+1,j,r+1,n,preorder, inorder);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0)
return null;
if(preorder.length==1)
return new TreeNode(preorder[0]);
TreeNode root = generate(0,preorder.length-1,0,inorder.length-1,preorder,inorder);
return root;
}
}
public class Solution {
private TreeNode generate(int i, int j, int m, int n, int[] postorder, int[] inorder){
if(i==j)
return new TreeNode(postorder[i]);
if(i>j)
return null;
TreeNode root = new TreeNode(postorder[i]);
int r;
for(r=m;r<=n;r++){
if(inorder[r]==postorder[i]){
root.right=generate(i+1,i+r-m,m,r-1,postorder,inorder);
break;
}
}
root.left=generate(i+r-m+1,j,r+1,n,postorder, inorder);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(postorder.length==0)
return null;
if(postorder.length==1)
return new TreeNode(postorder[0]);
int[] post = new int[postorder.length];
int[] in = new int[postorder.length];
for(int i=0;i<postorder.length;i++){
post[i] = postorder[postorder.length-1-i];
in[i] = inorder[postorder.length-1-i];
}
TreeNode root = generate(0,postorder.length-1,0,inorder.length-1,post,in);
return root;
}
}
Update 2015/09/01:第二题的做法有点繁琐,其实把两个数组从后往前数就相当于第一题的从右往左建立树。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
*@param inorder : A list of integers that inorder traversal of a tree
*@param postorder : A list of integers that postorder traversal of a tree
*@return : Root of a tree
*/
private TreeNode generate(int i, int j, int m, int n, int[] postorder, int[] inorder){
if(i==j)
return new TreeNode(postorder[i]);
if(i<j)
return null;
TreeNode root = new TreeNode(postorder[i]);
int r;
for(r=m;r>=n;r--){
if(inorder[r]==postorder[i]){
root.right=generate(i-1,i-m+r,m,r+1,postorder,inorder);
break;
}
}
root.left=generate(i-m+r-1,j,r-1,n,postorder, inorder);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
// write your code here
if(postorder.length==0)
return null;
TreeNode root = generate(postorder.length-1, 0,inorder.length-1, 0,postorder,inorder);
return root;
}
}