重建二叉树

重建二叉树

http://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6

使用前序遍历找到第一个是根节点
使用中序遍历找到根节点左边是左子树

/**
 * 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) {
        return build(pre, 0, pre.length - 1, in, 0, in.length - 1);
    }
    private TreeNode build(int[] pre, int l, int r, int[] in, int x, int y) {
        if (l > r) return null;
        int t = pre[l];
        int p = -1;
        for (int i = x; i <= y; i ++) {
            if (t == in[i]) p = i;
        }
        TreeNode node = new TreeNode(t);
        node.left = build(pre, l + 1, l + (p - x), in, x, p - 1);
        node.right = build(pre, l + (p - x) + 1, r, in, p + 1, y);
        return node;
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务