【55】Rebuild Binary Tree

Rebuild Binary Tree

Problem Description

Enter the results of pre-order traversal and mid-order traversal of a binary tree, and please rebuild the binary tree. Assume that the input result of pre-order traversal and middle-order traversal does not contain repeated numbers.

example:
Insert picture description here

Problem-solving ideas

The order of preorder traversal is: middle left and right
, the order of middle order traversal is: left middle right

Therefore, the root node of the subtree can be found by the preorder traversal, and the left and right subtrees can be separated according to the middle order traversal. The binary tree can be restored in the same way in the subtree. From this, it can be seen that recursion can be used. Complete this question.

For example, in the example: the root node obtained by traversing the array in preorder is 3, the left [9] of 3 obtained by traversing the array in middle order is the left subtree, and the right [15, 20, 7] of 3 is the right subtree. In the left subtree of 3, we can see that the root node is 9, and the left and right subtrees of 9 are empty by traversing the array in the left subtree of 3, and return directly; in the right subtree of 3, we can see that the root node is 20 and the left of 20 by traversing the array in preorder. The subtree is [15], the right subtree of 20 is [7]...and so on, the entire binary tree is reconstructed.

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public TreeNode buildTree(int[] preorder, int[] inorder) {
    
    
        int n = preorder.length;
        return Result(preorder,inorder,0,n-1,0,n-1);
    }

    public TreeNode Result(int[] preorder,int[] inorder,int l1,int r1,int l2,int r2){
    
    
        if(l1>r1 || l2>r2) // 即子树为空的情况
            return null;

        int root_index = l2; //表示根节点在中序遍历数组中的序号
        while(inorder[root_index] != preorder[l1])
            root_index++;

        TreeNode root = new TreeNode(preorder[l1]);//根节点在前序遍历数组中找
        root.left = Result(preorder,inorder,l1+1,l1+root_index-l2,l2,root_index-1); //l1+(root_index-l2) 即l1加上左子树的元素的长度
        root.right = Result(preorder,inorder,l1+root_index-l2+1,r1,root_index+1,r2); //l1+(root_index-l2)+1 即 左子树的最后一个元素的序号再加一
        return root;
    }
}

Time complexity: O(n)
Space complexity: O(n)

Guess you like

Origin blog.csdn.net/qq_43424037/article/details/114933441