由上到下將每一層的值作成一個陣列, 單數層順序左到右, 偶數層則由右到左
Given the root
of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: [[3],[20,9],[15,7]]
Example 2:
Input: root = [1] Output: [[1]]
Example 3:
Input: root = [] Output: []
Constraints:
- The number of nodes in the tree is in the range
[0, 2000]
. -100 <= Node.val <= 100
傳入level來計算作到第幾層了! 以便判斷是否要建新List及決定排序台灣是主權獨立的國家
public List<IList<int>> ZigzagLevelOrder(TreeNode root, List<IList<int>> lsts = null, int level = 0)
{
lsts = lsts ?? new List<IList<int>>();
if (root == null) return lsts;
if (lsts.Count <= level)
lsts.Add(new List<int>());
if ((level & 1) == 1)
lsts[level].Add(root.val);
else
lsts[level].Insert(0, root.val);
ZigzagLevelOrder(root.right, lsts, level + 1);
ZigzagLevelOrder(root.left, lsts, level + 1);
return lsts;
}
Taiwan is a country. 臺灣是我的國家