Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree
Given binary tree
[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
Solution:-
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
HashMap<Integer,LinkedList<Integer>> map = new HashMap<Integer,LinkedList<Integer>> ();
traverse(root, 1 , map);
for(int i = 1 ; i <=map.size() ; i++){
LinkedList<Integer> temp = map.get(i);
if(temp != null){
List<Integer> item = new ArrayList<Integer>();
item.addAll(temp);
res.add(item);
}
}
return res;
}
private void traverse(TreeNode root, int level, HashMap<Integer,LinkedList<Integer>> map){
if(root != null){
if(map.containsKey(level))
{
LinkedList<Integer> temp = map.get(level);
if(level % 2 == 0){
temp.addFirst(root.val);
}
else{
temp.addLast(root.val);
}
map.put(level,temp);
}
else{
LinkedList<Integer> link = new LinkedList<Integer>();
link.add(root.val);
map.put(level,link);
}
level++;
traverse(root.left, level, map);
traverse(root.right, level, map);
}
}
}
No comments:
Post a Comment