Leetcode 103: Binary Tree Zigzag Level Order Traversal
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] ]
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public IList<IList<int>> ZigzagLevelOrder(TreeNode root) { 12 var result = new List<IList<int>>(); 13 14 if (root == null) return result; 15 16 var q = new Queue<TreeNode>(); 17 q.Enqueue(root); 18 var count = q.Count; 19 bool zig = true; 20 21 while (q.Count > 0) 22 { 23 var r = new List<int>(); 24 25 for (int i = 0; i < count; i++) 26 { 27 var t = q.Dequeue(); 28 29 if (zig) 30 { 31 r.Add(t.val); 32 } 33 else 34 { 35 r.Insert(0, t.val); 36 } 37 38 if (t.left != null) q.Enqueue(t.left); 39 if (t.right != null) q.Enqueue(t.right); 40 } 41 42 result.Add(r); 43 count = q.Count; 44 zig = !zig; 45 } 46 47 return result; 48 } 49 }

浙公网安备 33010602011771号