p103

LeetCode p103 Binary Tree Zigzag Level Order Traversal 题解

1.题目:

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 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]

题意:

输入一二叉树,返回他每层元素的列表,奇数列从左到右,偶数列从右到左。

2.解题思路:

前续遍历

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
/**
* 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>> ans = new ArrayList<List<Integer>>();

public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
zigzagLevelOrder(root, 0);
return ans;
}

public void zigzagLevelOrder(TreeNode root, int count) {
if (root == null)
return;

if (ans.size() <= count) {
ans.add(new ArrayList<Integer>());
}
List<Integer> a = ans.get(count);
if(count % 2 == 0) a.add(root.val);
else a.add(0, root.val);
zigzagLevelOrder(root.left, count + 1);
zigzagLevelOrder(root.right, count + 1);


}
}

4.一些总结: