[LeetCode|[LeetCode 103] Zigzag Traversal (medium)
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).
【[LeetCode|[LeetCode 103] Zigzag Traversal (medium)】For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
920
/\
157
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> zigzagLevelOrder(TreeNode root) {
List> result = new ArrayList<> ();
if (root == null) {
return result;
}Stack tracker1 = new Stack<> ();
Stack tracker2 = new Stack<> ();
int layer = 1;
List 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 ();
tracker1 = tracker2;
tracker2 = new Stack ();
layer++;
}}return result;
}
}
推荐阅读
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- leetcode|leetcode 92. 反转链表 II
- 20210307《挑战赛怂人胆》【能量将帅挑战赛(01)】
- 103
- 二叉树路径节点关键值和等于目标值(LeetCode--112&LeetCode--113)
- LeetCode算法题-11.|LeetCode算法题-11. 盛最多水的容器(Swift)
- LeetCode(03)Longest|LeetCode(03)Longest Substring Without Repeating Characters
- 《我怎样教语文》读书打卡(十九)20210317
- 鬼故事
- Leetcode|Leetcode No.198打家劫舍