Wins the offer-004- rebuild binary tree

topic:

And enter the result in a preorder traversal of a binary tree in preorder traversal of the binary tree a rebuild. Suppose Results preorder traversal order and input of duplicate numbers are free. Before entering e.g. preorder traversal sequence {1,2,4,7,3,5,6,8} and {4,7,2,1,5,3,8,6} order traversal sequence, and the reconstructed binary tree return.

Ideas:

According to the preamble sequence, to find the root node.

Sequence in order to find the position of the root node, the sequence is divided into right and left halves.

Respectively recursive solution left subtree, right subtree, return to the root.

time complexity:

O (nlogn)

According to the recursive formula, T (n) = 2T (n / 2) + O (n)

The problem is divided into two sub-problems, each sub-scale of the problem is T (n / 2). In each work O (n) sub-problems, that is, find the location of the root node.

The use of Master Theorem, can be introduced O (nlogn)

 

Code:

import java.util.Arrays;
/**
 * 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) {
        
        if(pre.length == 0 || in.length == 0) {
            return null;
        }
        
        TreeNode root = new TreeNode(pre[0]);
        
        // find the position of root in in[]
        int pos = 0;
        for (int i =0; i < in.length; i++) {
            if(in[i] == pre[0]) {
                pos = i;
            }
        }
 
        root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, 1 + pos), Arrays.copyOfRange(in, 0, pos));
        root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, 1 + pos, pre.length), Arrays.copyOfRange(in, pos + 1, in.length));
        
        return root;
    }
}

 

Guess you like

Origin www.cnblogs.com/zyrJessie/p/12590754.html