"Prove safety offer" face questions 6 binary tree reconstruction

"Prove safety offer" answers, analysis and notes for Java
"wins the offer" is inscribed 6: reconstruction of a binary tree (from the preamble sequence and a sequence of binary tree to rebuild a binary tree)

The book Methods: We want to reconstruct a binary tree, we must continue to find root and left child node and the right child of the root node. Note that the preamble sequence , its first element is the root node, back into binary elements preorder traversal and right subtree preorder traversal of its left subtree. The question now is if the preamble sequence alone, we can only find the root, but we do not know the length of the two sub-sequences , we will not be able to continue to find the root of the subtree the same way. This time we need an auxiliary sequence - the sequence order , according to its characteristics, the root node must be in the middle of the left and right sequences of sequences, so that we can determine the length of the two sequences.

    public TreeNode build(int[] a, int[] b){
        if(a.length == 0){
            return null;
        }
        return build(a, 0, a.length-1, b, 0, b.length-1);
    }
    
    private TreeNode build(int[] a, int aStart, int aEnd, int[] b, int bStart, int bEnd){
        if(aStart > aEnd)return null;
        //构建根节点
        TreeNode root = new TreeNode(a[aStart]);
        //找到根节点在中序序列中的位置
        int partition = bStart;
        for(int i=bStart; i<=bEnd; i++){
            if(b[i] == a[aStart]){
                partition = i;
                break;
            }
        }
        //在左子序列中继续构建根节点
        root.left = build(a, aStart+1, aStart+1+partition-1-bStart,
                b, bStart, partition-1);
        //在右子序列中继续构建根节点
        root.right = build(a, aStart+partition-bStart+1, aEnd,
                b, partition+1, bEnd);
        //返回构建好的根节点
        return root;
        
    }

NOTE: Only used in preamble sequence + + or subsequent reconstruction of the binary sequence, a preamble sequence + the reconstructed binary tree is not unique, since the sequence after the last element of the first sequence before and after the sequence is not always determined sequence in the end it is still left subtree right subtree front element of representation. For example, only a left subtree binary 3 <-2 <1, and only a right subtree binary 1-> 2-> 3, their sequence and the preamble sequence is the same.

Guess you like

Origin www.cnblogs.com/czjk/p/11589869.html