Leetcode depth first search constructs binary tree from pre-order and middle-order traversal sequence java

Topic description
Construct a binary tree based on the pre-order traversal and middle-order traversal of a tree.
Note:
You can assume that there are no duplicate elements in the tree.

For example, given the
preorder traversal preorder = [3,9,20,15,7] the
inorder traversal inorder = [9,3,15,20,7]
returns the following binary tree:

3

/
9 20
/
15 7

Method:
Pre-order traversal and middle-order traversal are as follows:
Insert picture description here
use preLeft to indicate the starting index of the pre-order traversal sequence, preRight to indicate the ending index of the pre-order traversal sequence, inLeft to indicate the starting index of the in-order traversal sequence, and inRight to indicate The termination subscript of the middle-order traversal sequence. In the
pre-order traversal, the root node is the first to be visited. Therefore, the first node of the pre-order traversal sequence is the root. The node values ​​and subscripts of the middle-order traversal are stored in a map. Find the position pIndex of the root node in the map, then the corresponding left subtree (inLeft——pIndex-1) and right subtree (pIndex+1——inRight) can be determined, and then the length of the left subtree can be obtained as ( pIndex-inLeft), after the length of the left subtree is obtained, the boundary between the left subtree and the right subtree in the preorder traversal sequence can be further obtained. As shown below:
Insert picture description here
Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    //map存放中序遍历序列的节点值和对应的下标
    private Map<Integer,Integer> indexmap = new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
    
    
        int n = inorder.length;
        for(int i = 0;i<n;i++){
    
    
            indexmap.put(inorder[i],i);
        }
        return mybuildTree(preorder,inorder,0,n-1,0,n-1);

    }
    public TreeNode mybuildTree(int[] preorder,int[] inorder,int pre_left,int pre_right,int in_left,int in_right){
    
    
        if(pre_left > pre_right){
    
    
            return null;
        }
        //第一个节点即为根节点
        int pre_root = pre_left;
        //在中序遍历序列中找到根节点对应的下标p_index
        int p_index = indexmap.get(preorder[pre_root]);
       //根节点
        TreeNode root = new TreeNode(preorder[pre_root]);
        //左子树的大小
        int left_size = p_index - in_left;
        root.left = mybuildTree(preorder,inorder,pre_left+1,pre_left+left_size,in_left,p_index-1);
        root.right = mybuildTree(preorder,inorder,pre_left+left_size+1,pre_right, p_index+1,in_right);
        return root;
    }
}

Guess you like

Origin blog.csdn.net/stonney/article/details/110891916