Construct Binary Tree from Inorder and Postorder Traversal

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

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

给定中序遍历和后序遍历的序列,还原树。


代码如下:

public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
		if(inorder==null||inorder.length==0)
        	return null;
        return buildRoot(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);
    }
	
	public int findIndex(int[] inorder,int target){
		for(int i=0;i<inorder.length;i++){
			if(inorder[i]==target)
				return i;
		}
		return 0;
	}
	
	public TreeNode buildRoot(int[] inorder,int inleft,int inright,int[] postorder,int postleft,int postright){
		if(inleft==inright)
			return new TreeNode(inorder[inleft]);
		if(inleft>inright)
			return null;
		TreeNode root=new TreeNode(postorder[postright]);
		int index=findIndex(inorder, postorder[postright]);
		root.left=buildRoot(inorder, inleft, index-1, postorder, postleft, postleft+index-inleft-1);//注意这里的位置都是用长度和起点来算
		root.right=buildRoot(inorder, index+1, inright, postorder, postleft+index-inleft, postright-1);
		return root;
	}
}


你可能感兴趣的:(java,LeetCode,tree)