zoukankan      html  css  js  c++  java
  • 104.求二叉树的最大深度 Maximum Depth of Binary Tree

    求二叉树的最大深度

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using Algorithm;
    6. namespace Solution {
    7. public class Solution1 {
    8. public int MaxDepth(TreeNode root) {
    9. if (root == null) return 0;
    10. int left = MaxDepth(root.left) + 1;
    11. int right = MaxDepth(root.right) + 1;
    12. return left > right ? left : right;
    13. }
    14. }
    15. public class Solution2 {
    16. public int MaxDepth(TreeNode root) {
    17. if (root == null) return 0;
    18. return Math.Max(MaxDepth(root.left), MaxDepth(root.right)) + 1;
    19. }
    20. }
    21. public class Solution3 {
    22. public int MaxDepth(TreeNode root) {
    23. if (root == null) return 0;
    24. int depth = 0;
    25. Queue<TreeNode> queue = new Queue<TreeNode>();
    26. queue.Enqueue(root);
    27. while (queue.Count > 0) {
    28. int count = queue.Count;
    29. for (int i = 0; i < count; i++) {
    30. TreeNode node = queue.Dequeue();
    31. if (node.left != null) queue.Enqueue(node.left);
    32. if (node.right != null) queue.Enqueue(node.right);
    33. }
    34. depth++;
    35. }
    36. return depth;
    37. }
    38. }
    39. class Program {
    40. static void Main(string[] args) {
    41. Solution s = new Solution2();
    42. int?[] arr = { 1, 2, 3, 4, 5, null, 6, 7, 8, null, null, 9, 10 };
    43. TreeNode root = Tree.CreateTree(arr);
    44. int res = s.MaxDepth(root);
    45. Console.Write(res);
    46. }
    47. }
    48. }






  • 相关阅读:
    java的反射机制浅谈 分类: java
    2.4.3 Cow Tours
    2.4.2 Overfencing
    2.4.1 The Tamworth Two
    Shortest Paths
    2.3.5 Controlling Companies
    2.3.4 Money Systems
    2.3.3 Zero Sum
    2.3.2 Cow Pedigrees
    2.3.1 Longest Prefix
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/a70bc591d27f343ec38bc1c592911f2f.html
Copyright © 2011-2022 走看看