4、重建二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NCUscienceZ/article/details/84260550

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode build(int[] pre, int[] in, int LP, int RP, int LI, int RI){
        if(LP > RP) return null;
        
        int root = pre[LP];
        int t = 0;
        while(in[t] != root) t++;
        int cnt = t-LI;
        TreeNode ans = new TreeNode(root);
        ans.left = build(pre, in, LP+1, LP+cnt, LI, t-1);
        ans.right = build(pre, in, LP+cnt+1, RP, t+1, RI);
        return ans;
    }
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        return build(pre, in, 0, pre.length-1, 0, in.length-1);
    }
}

老掉牙题目了。

数组长度又犯了错误!!!要想获得数组中的元素个数, 可以使用 array . length 。没有(),没有(),没有()!!!

猜你喜欢

转载自blog.csdn.net/NCUscienceZ/article/details/84260550