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. }






posted @ 2017-01-10 23:00  xiejunzhao  阅读(113)  评论(0编辑  收藏  举报