根据给定的Node树节点,返回包含按级别排序的树中元素的列表,这意味着根元素位于第一位,然后根子元素(从左到右)位于第二位和第三位,依此类推。
1 public class Node 2 { 3 public Node Left; 4 public Node Right; 5 public int Value; 6 7 public Node(Node l, Node r, int v) 8 { 9 Left = l; 10 Right = r; 11 Value = v; 12 } 13 } 14 15 示例1 : 16 17 2 18 8 9 19 1 3 4 5 20 需要返回list: 21 22 [2,8,9,1,3,4,5] 23 示例2 : 24 25 1 26 8 4 27 3 5 28 7 29 需要返回list: 30 31 [1,8,4,3,5,7]
算法实现:
1 using System; 2 using System.Collections.Generic; 3 4 public class Kata 5 { 6 public static List<int> TreeByLevels(Node root) 7 { 8 List<int> result = new List<int>(); 9 10 if (root == null) 11 return result; 12 13 Queue<Node> queue = new Queue<Node>(); 14 queue.Enqueue(root); 15 16 while (queue.Count > 0) 17 { 18 Node node = queue.Dequeue(); 19 result.Add(node.Value); 20 21 if (node.Left != null) 22 queue.Enqueue(node.Left); 23 if (node.Right != null) 24 queue.Enqueue(node.Right); 25 } 26 27 return result; 28 } 29 }
测试用例:
1 [Test] 2 public void SingleNodeTest() 3 { 4 Assert.AreEqual(new List<int>() { 1 }, Kata.TreeByLevels(new Node(null, null, 1))); 5 } 6 7 [Test] 8 public void LeftSkewedTreeTest() 9 { 10 Assert.AreEqual(new List<int>() { 1, 2, 3, 4, 5 }, Kata.TreeByLevels(new Node(new Node(new Node(null, null, 4), null, 2), null, 1))); 11 } 12 13 [Test] 14 public void RightSkewedTreeTest() 15 { 16 Assert.AreEqual(new List<int>() { 1, 2, 3, 4, 5 }, Kata.TreeByLevels(new Node(null, new Node(null, new Node(null, null, 5), 3), 1))); 17 } 18 19 [Test] 20 public void CompleteBinaryTreeTest() 21 { 22 Assert.AreEqual(new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, Kata.TreeByLevels(new Node( 23 new Node(new Node(null, null, 4), new Node(null, null, 5), 2), 24 new Node(new Node(null, null, 6), new Node(null, null, 7), 3), 25 1))); 26 } 27 28 [Test] 29 public void SkewedTreeWithNullNodesTest() 30 { 31 Assert.AreEqual(new List<int>() { 1, 2, 3, 4, 5 }, Kata.TreeByLevels(new Node( 32 new Node(null, null, 2), 33 null, 34 1))); 35 } 36 37 /*这些测试用例覆盖了一些特殊情况,包括: 38 39 - 单个节点的情况; 40 - 左倾斜的树(即只有左子树的树)的情况; 41 - 右倾斜的树(即只有右子树的树)的情况; 42 - 完全二叉树的情况; 43 - 包含空节点(null)的树的情况。 44 45 通过这些测试用例,可以验证算法在各种情况下的正确性和鲁棒性。*/