根据二叉树中序和后序(先序)遍历结果 重建二叉树

题目描述
根据中序遍历和后序遍历构造二叉树
From the post-order array, we know that last element is the root. We can find the root in in-order array. Then we can identify the left and right sub-trees of the root from in-order array.

Using the length of left sub-tree, we can identify left and right sub-trees in post-order array. Recursively, we can build up the tree

public TreeNode buildTree(int[] inorder, int[] postorder) {
    int inStart = 0;
    int inEnd = inorder.length - 1;
    int postStart = 0;
    int postEnd = postorder.length - 1;

    return buildTree(inorder, inStart, inEnd, postorder, postStart, postEnd);
}

public TreeNode buildTree(int[] inorder, int inStart, int inEnd,
        int[] postorder, int postStart, int postEnd) {
    if (inStart > inEnd || postStart > postEnd)
        return null;

    int rootValue = postorder[postEnd];
    TreeNode root = new TreeNode(rootValue);

    int k = 0;
    for (int i = 0; i < inorder.length; i++) {
        if (inorder[i] == rootValue) {
            k = i;
            break;
        }
    }

    root.left = buildTree(inorder, inStart, k - 1, postorder, postStart,
            postStart + k - (inStart + 1));
    // Becuase k is not the length, it it need to -(inStart+1) to get the length
    root.right = buildTree(inorder, k + 1, inEnd, postorder, postStart + k- inStart, postEnd - 1);
    // postStart+k-inStart = postStart+k-(inStart+1) +1

    return root;
}

/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }

根据先序遍历和中序遍历构造二叉树

 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        TreeNode root = reconstructBTNode(pre,0,pre.length-1, in, 0, in.length-1);
        return root;
    }
      public static TreeNode reconstructBTNode(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn){
        if(startPre > endPre || startIn > endIn)  return null;
        //重建根结点
        TreeNode root = new TreeNode(pre[startPre]);
        //根据root.val 在中序序列中确定根结点的位置下标i;
        for(int i = startIn ; i < in.length; i++){
            if(in[i] == root.val){
                //左子树序列
                root.left = reconstructBTNode(pre, startPre+1, startPre+i-startIn, in ,startIn, i-1);
                //右子树序列
                root.right = reconstructBTNode(pre,startPre+i-startIn+1, endPre, in , i+1, endIn);
            }
        }
        return root;
    } 
}
点赞