Java LeetCode 106. Construct a binary tree from middle order and post order traversal sequence

The binary tree is constructed according to the middle-order traversal and post-order traversal of a tree.
Note:
You can assume that there are no duplicate elements in the tree.
For example, given
inorder traversal inorder = [9,3,15,20,7]
traversal postorder = [9,15,7,20,3]

Insert picture description here

First define a map, the key is used to store the value in the middle-order traversal array, and the value is stored in the location

Insert picture description here
Insert picture description here

This graph is very important, because the last element of the post-order traversal must be the root node. The position of the root node in the middle-order traversal can be found through the value in the root node map. The left subtree of the root node is the left subtree, and the right subtree is the right subtree.

Then at the same time, the positions of the left subtree and the right subtree can be found in the post-order traversal through the middle-order traversal, that is, through these two sub-trees, the root nodes of the two sub-trees can be found through the post-order traversal rules again, and then through this root node You can find the position of the left subtree and the right subtree in the middle order traversal, so that recursion can be performed

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    Map<Integer,Integer> map = new HashMap();
    int post[];
    public TreeNode buildTree(int[] inorder, int[] postorder) {
    
    
        post = postorder;
        for(int i=0;i<inorder.length;i++){
    
    
            map.put(inorder[i],i);
        }
        return reverse(0,inorder.length-1,0,post.length-1);
    }
    public TreeNode reverse(int ll,int lr,int rl,int rr){
    
    
        if(ll>lr||rl>rr){
    
    
            return null;
        }
        TreeNode tree = new TreeNode(post[rr]);
        int zd = map.get(post[rr]);
        tree.left = reverse(ll,zd-1,rl,rl+zd-ll-1);
        tree.right= reverse(zd+1,lr,rl+zd-ll,rr-1);
        return tree;
    }
}

Guess you like

Origin blog.csdn.net/sakura_wmh/article/details/110150984