Tuesday, November 3, 2015

[leetcode]Binary Tree Zigzag Level Order Traversal

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class Solution {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        dfsLevel(root, 0);
        return result;
    }
    private void dfsLevel(TreeNode root, int level){
     if (root == null) return;
     if (result.size() < level+1) result.add(new ArrayList<Integer>());
     if (level % 2 == 0)result.get(level).add(root.val);
     else result.get(level).add(0, root.val);
     dfsLevel(root.left, level+1);
     dfsLevel(root.right, level+1);
    }
}

No comments:

Post a Comment