Given a binary tree, and return to its node value to traverse from the bottom of the bottom. (That is, according to the layer from the layer of the leaf node to the layer where the root node is located, it traversed from left to right)
For example:
Gives binary tree [3,9,20, null, null, 15,7],
Return to its upward level from the bottom of the traversal:
[
[15,7],
[9,20],
[3]
]
Question 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);
}
}