Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree
Given binary tree
[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
Solution:-
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
HashMap<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();
traversal(root,map, 0);
List<List<Integer>> res = new ArrayList<List<Integer>>();
int level = map.size();
for(int i = level ; i >=0 ; i--){
List<Integer> temp = map.get(i);
if(temp != null){
res.add(temp);
}
}
return res;
}
private void traversal(TreeNode root, HashMap<Integer,List<Integer>> map, int level){
if(root != null){
if(map.containsKey(level)){
List<Integer> temp = map.get(level);
temp.add(root.val);
map.put(level,temp);
}
else{
List<Integer> temp = new ArrayList<Integer>();
temp.add(root.val);
map.put(level,temp);
}
traversal(root.left, map, level + 1);
traversal(root.right, map, level + 1);
}
}
}
No comments:
Post a Comment