2017.9.8
这个和
前序遍历和中序遍历树构造二叉树
是差不多的/**
* 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
*/
public TreeNode buildTree(int[] inorder, int[] postorder) {
// write your code here
if(inorder == null || postorder == null || inorder.length != postorder.length || inorder.length == 0){
return null;
}
TreeNode root = new TreeNode(postorder[postorder.length-1]);
for(int i = 0; i < inorder.length; i++){
if(inorder[i] == root.val){
int []inLeft = Arrays.copyOfRange(inorder, 0, i);
int []inRight = Arrays.copyOfRange(inorder, i+1, inorder.length);
int []postRight = Arrays.copyOfRange(postorder, inLeft.length, postorder.length-1);
int []postLeft = Arrays.copyOfRange(postorder, 0, inLeft.length);
root.left = buildTree(inLeft,postLeft);
root.right = buildTree(inRight,postRight);
}
}
return root;
}
}