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]
]
Solution
- 关于Tree 和 Level,用BFS, 思路与102类似,用2个
queue
或stack
- 但是题目要求的是
zigzag level order
, 先入后出,所以这里需要用stack
. - 而且,如果假设TREE只有一个根节点时,其层数为1。
---- 偶数层,在向stack2
加入新节点时,先add right
再add left
.
---- 奇数层,在向stack2
加入新节点时,先add left
再add right
.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<> ();
if (root == null) {
return result;
}
Stack<TreeNode> tracker1 = new Stack<> ();
Stack<TreeNode> tracker2 = new Stack<> ();
int layer = 1;
List<Integer> subArray = new ArrayList<> ();
tracker1.add (root);
while (!tracker1.isEmpty ()) {
TreeNode current = tracker1.pop ();
subArray.add (current.val);
if (layer % 2 != 0) {
if (current.left != null) {
tracker2.push (current.left);
}
if (current.right != null) {
tracker2.push (current.right);
}
} else if (layer % 2 == 0) {
if (current.right != null) {
tracker2.push (current.right);
}
if (current.left != null) {
tracker2.push (current.left);
}
}
if (tracker1.isEmpty ()) {
result.add (subArray);
subArray = new ArrayList<Integer> ();
tracker1 = tracker2;
tracker2 = new Stack<TreeNode> ();
layer++;
}
}
return result;
}
}