Learn Algorithms with Me Series 6---Rebuild Binary Tree

1. Topic description
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.

2. Algorithm Analysis
First, we need to understand what is preorder and inorder traversal. In the preorder traversal sequence of a binary tree, the first number must be the value of the root node of the tree, followed by the left subtree and the right subtree. In an inorder traversal sequence, the value of the root node must be in the middle of the sequence, the left side of the root node is the value of the node of the left subtree, and the right side of the root node is the value of the node of the right subtree.

Therefore, the idea of ​​solving this problem is to scan the in-order traversal sequence, find the value of the root node, and then find the pre-order traversal sequence and in-order traversal sequence of the left and right subtrees according to the position of the root node, and use the same method. To build the left and right subtrees separately, that is, to complete it in a recursive form.

3. Code example

/**
 * 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) {
        TreeNode root = reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
        return root;
    }
    
    //前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
    private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) {

        if(startPre > endPre || startIn > endIn)
            return null;
        TreeNode root = new TreeNode(pre[startPre]);

        for(int i = startIn;i <= endIn;i++)
            if(in[i] == pre[startPre]){
                root.left = reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
                root.right = reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
            }

        return root;
    }
}

Guess you like

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