2014年10月8日星期三

[Leetcode] Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
和用中序和后续来重建树的方法是一样的。
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int n = inorder.length;
        if(n == 0) return null;
        if(n == 1) return new TreeNode(inorder[0]);
        int key = preorder[0];
        int ind = 0;
        while(inorder[ind] != key) ind++;
        
        int[] il = new int[ind];
        int[] pl = new int[ind];
        int[] ir = new int[n-1-ind];
        int[] pr = new int[n-1-ind];
        for(int i = 0; i < ind; i++) {
            il[i] = inorder[i];
            pl[i] = preorder[i+1];
        }
        for(int i = 0; i < n-1-ind; i++) {
            ir[i] = inorder[ind+1+i];
            pr[i] = preorder[ind+1+i];
        }
        TreeNode root = new TreeNode(key);
        root.left = buildTree(pl ,il);
        root.right = buildTree(pr, ir);
        return root;
    }

没有评论:

发表评论