题意:

image.png

解题思路:

  1. 思路:
  2. 递归(dfs):O(n):树中的每个节点遍历一次
  3. 1. 递归求左右子树高度最大值,直到子树为空,最后返回该最大值;

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param TreeNode $root
  4. * @return Integer
  5. */
  6. function maxDepth($root) {
  7. if ($root == null) return 0;
  8. return max($this->maxDepth($root->left), $this->maxDepth($root->right)) + 1;
  9. //return $this->maxDepthIterative($root);
  10. if (!$root) return 0;
  11. return max($this->getHeight($root->left), $this->getHeight($root->right)) + 1;
  12. }
  13. function getHeight($root) {
  14. if ($root == null) return 0;
  15. $left = $this->getHeight($root->left);
  16. $right = $this->getHeight($root->right);
  17. return max($left, $right) + 1;
  18. }
  19. function maxDepthIterative($root) {
  20. if ($root == null) return 0;
  21. $queue = [];
  22. array_push($queue, $root);
  23. $depth = 0;
  24. while (!empty($queue)) {
  25. foreach ($queue as $r) {
  26. if ($r->left != null) array_push($queue, $r->left);
  27. if ($r->right != null) array_push($queue, $r->right);
  28. array_shift($queue);
  29. }
  30. ++$depth;
  31. }
  32. return $depth;
  33. }
  34. }

GO代码实现:

  1. func maxDepth(root *TreeNode) int {
  2. if root == nil {
  3. return 0
  4. }
  5. return max(maxDepth(root.Left), maxDepth(root.Right)) + 1
  6. }
  7. func max(a int, b int) int {
  8. if a > b {
  9. return a
  10. }
  11. return b
  12. }
  13. func maxDepth(root *TreeNode) int {
  14. if root == nil {
  15. return 0
  16. }
  17. var result int
  18. queue := make([]*TreeNode,0)
  19. queue = append(queue,root)
  20. for len(queue) != 0 {
  21. levelLength := len(queue)
  22. for levelLength > 0 {
  23. levelLength--;
  24. node := queue[0] // 出队
  25. queue = queue[1:]
  26. if node.Left != nil {
  27. queue = append(queue,node.Left)
  28. }
  29. if node.Right != nil {
  30. queue = append(queue,node.Right)
  31. }
  32. }
  33. result++;
  34. }
  35. return result
  36. }