LeeCode105 traverses the binary tree (Java) from preorder and middle order traversal (recursive)

Topic link: LeeCode105 traverses the binary tree from the pre-order and middle-order traversal.
Topic description: Insert picture description here
This question really tortures me, because I don’t understand the pre-order and middle-order concepts very well. I don’t have this concept in my mind, and it takes me two days. , Finally, I watched the video and watched the solution and finally figured it out.
Pre-order traversal is root->left sequence->right sequence
Middle-order traversal is left sequence->root->right sequence. The
approach is equivalent to traversing the pre-order. The subscript of the current sequence is in front of the middle-order sequence. When you click, the preorder sequence is followed by his right subtree sequence.
Every time the head of the preorder sequence is taken, it is the root node of the current traversal, and then the left and right sequences are separated according to the root node.

class Solution {
    
    
    public static TreeNode buildTree(int[] preorder, int[] inorder) {
    
    
        Map<Integer,Integer> map=new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
    
    
        	//储存中序序列中每一个数据对应的下标
            map.put(inorder[i],i);
        }
        return mytree(preorder,0,preorder.length,inorder,0,inorder.length,map);
    }
    public static TreeNode mytree(int[] preorder,int pre_start,int pre_end,int[] inorder,int in_start,int in_end,Map<Integer,Integer> map){
    
    
        //pre_start每次都是当前序列开始下标加1,pre_end是中序根节点前面的长度+pre_start,所以就是当中序中左或右为空返回
        if(pre_start>=pre_end) return null;
        //获取根节点下标
        Integer integer = map.get(preorder[pre_start]);
        //把当前的节点当作根节点
        TreeNode root=new TreeNode(preorder[pre_start]);
        //中序中根节点减开始位置即下一个序列长度
        int len=integer-in_start;
        root.left=mytree(preorder, pre_start+1, pre_start+len+1, inorder, in_start, integer, map);
        root.right=mytree(preorder, pre_start+len+1, pre_end, inorder, integer+1, in_end, map);
        return root;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43590593/article/details/113044268