LeetCode Online Judge 题目C# 练习 - Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
1 public static List<List<int>> BinaryTreeLevelOrderTraversal(BTNode root) 2 { 3 List<List<int>> ret = new List<List<int>>(); 4 if (root == null) 5 return ret; 6 7 Queue<BTNode> read = new Queue<BTNode>(); 8 Queue<BTNode> write = new Queue<BTNode>(); 9 10 read.Enqueue(root); 11 12 while (read.Count > 0) 13 { 14 List<int> level = new List<int>(); 15 while (read.Count > 0) 16 { 17 BTNode temp = read.Dequeue(); 18 level.Add(temp.Value); 19 20 if (temp.Left != null) 21 { 22 write.Enqueue(temp.Left); 23 } 24 if (temp.Right != null) 25 { 26 write.Enqueue(temp.Right); 27 } 28 } 29 30 ret.Add(level); 31 32 //swap read and write 33 Queue<BTNode> tempQ = read; 34 read = write; 35 write = tempQ; 36 } 37 38 return ret; 39 }
代码分析:
用两个Queue,交叉enqueu,dequeue出来的就放到一个 List<int> 中,在放到List<List<int>>中。