leetcode107 (Hierarchical Traversal of Binary Tree II: DFS Deep Search)

Given a binary tree, return its node value to traverse the bottom up. (That is, from the layer where the leaf node is located to the layer where the root node is located, traverse from left to right layer by layer)

For example:
Given a binary tree [3,9,20,null,null,15,7],

Return its bottom-up level traversal as:
[
[15,7],
[9,20],
[3]
]

Solution: Use DFS deep search + hash storage, DFS deep search to traverse the binary tree, and use the hash table to store the nodes of each layer.

class Solution {
    
    
     int layerTotal=0;
     List<List<Integer>>res=new ArrayList<>();
     public List<List<Integer>> levelOrderBottom(TreeNode root) {
    
    
        Map<Integer,List<Integer>>map=new HashMap<>();
        DFS(map,1,root);
        for(int i=layerTotal;i>=1;i--){
    
    
            if(map.containsKey(i)) 
                res.add(map.get(i));
        }
        return res;
     }
    private void DFS(Map<Integer,List<Integer>>map,int layer,TreeNode node){
    
    
        if(node==null)
            return;
        layerTotal=Math.max(layer,layerTotal);
        List<Integer>temp=map.getOrDefault(layer,new ArrayList<>());
        temp.add(node.val);
        map.put(layer,temp);
        DFS(map,layer+1,node.left);
        DFS(map,layer+1,node.right);
    }
}

Guess you like

Origin blog.csdn.net/CY2333333/article/details/108427540