每日一道:四數之和
阿新 • • 發佈:2021-11-25
二叉樹:
1.獲取樹的深度
class Program { static void Main(string[] args) { Node root = new Node() { Value = 1 }; Node level21 = new Node() { Value = 2 }; Node level22 = new Node() { Value = 3 }; Node level31 = new Node() { Value = 4 }; Node level32 = new Node() { Value = 5把圈子變小,把語言變乾淨,把成績往上提,把故事往心裡收,現在想要的以後你都會有。}; Node level33 = new Node() { Value = 6 }; Node level41 = new Node() { Value = 7 }; Node level51 = new Node() { Value = 8 }; root.LeftChild = level21; root.RightChild = level22; level21.LeftChild = level31; level22.LeftChild = level32; level22.RightChild= level33; level32.RightChild = level41; level41.LeftChild = level51; int treeDepth = GetTreeDepth(root); //int treeDepth = GetTreeDepthByLoop(root); Console.WriteLine(treeDepth); Console.ReadKey(); } static int GetTreeDepth(Node root) {if (root == null) return 0; int leftchilDeepth = GetTreeDepth(root.LeftChild); int rightchilDeepth = GetTreeDepth(root.RightChild); return leftchilDeepth > rightchilDeepth ? leftchilDeepth + 1 : rightchilDeepth + 1; } static int GetTreeDepthByLoop(Node root) { if (root == null) return 0; int deepth = 1; List<Node> list1 = new List<Node>(); List<Node> list2 = new List<Node>(); List<Node> temp; list1.Add(root); while (true) { foreach (var node in list1) { if (node.LeftChild != null) list2.Add(node.LeftChild); if (node.RightChild != null) list2.Add(node.RightChild); } if (list2.Count > 0) deepth++; else return deepth; list1.Clear(); temp = list1; list1 = list2; list2 = temp; } } } #region Tree class Node { public int Value { get; set; } public Node LeftChild { get; set; } public Node RightChild { get; set; } } #endregion