Preorder Inorder Reconstruction Binary Tree

Question: Input the results of preorder traversal and inorder traversal of a binary tree, please reconstruct the binary tree. It is assumed that the results of the input preorder traversal and inorder traversal do not contain duplicate numbers. For example, input the preorder traversal sequence {1,2,4,7,3,5,6,8} and the inorder traversal sequence {4,7,2,1,5,3,8,6}, then rebuild the binary tree and return

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
//Arrays.copyOfRange(T[ ] original,int from,int to) 从from到to,包含from不包含to
import java.util.Arrays;
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]);
        for(int i=0;i<in.length;i++){
            if(in[i]==pre[0]){
                root.left=reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(in,0,i));
                root.right=reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),Arrays.copyOfRange(in,i+1,in.length));
               // break;
            }
        }
        return root;
    }
}
  • The Arrays.copyOfRange(T[ ] original,int from,int to) function in java goes from from to to, including from but not including to

  • This method is very useful in some programming problems dealing with arrays. The efficiency is basically the same as that of clone. Both are native methods, which are much more efficient than using loops to copy arrays.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324749405&siteId=291194637