Reconstruction binary tree (the sequence preorder tree reduction)

Description Title
input result and the 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.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode solve(int pre[],int in[],int root,int inL,int inR){
        if(inL>=inR) return null;
        TreeNode tr=new TreeNode(pre[root]);
        for(int i=inL;i<inR;i++){
            if(in[i]==pre[root]){
                root++;
                tr.left=solve(pre,in,root,inL,i);
                tr.right=solve(pre,in,root+i-inL,i+1,inR);
                break;
            }
        }
        return tr;
    }
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        return solve(pre,in,0,0,in.length);
    }
}
Published 428 original articles · won praise 55 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_42936517/article/details/105180346