题意:

image.png

解题思路:

  1. 思路:每个节点仅被遍历一次,且遍历时所有操作的复杂度是 O(1),所以总时间复杂度是 O(n)
  2. 1. 如果root左右节点都为空,则返回1
  3. 2. 如果root左节点为空,则递归求右子树节点的深度+1
  4. 3. 如果root右节点为空,则递归求左子树的深度+1
  5. 4. root节点左右孩子都不为空时,返回左右子树较小深度的节点值+1(加上根节点这层)

PHP代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * class TreeNode {
  4. * public $val = null;
  5. * public $left = null;
  6. * public $right = null;
  7. * function __construct($value) { $this->val = $value; }
  8. * }
  9. */
  10. class Solution {
  11. /**
  12. * @param TreeNode $root
  13. * @return Integer
  14. */
  15. function minDepth($root) {
  16. return $this->minDepthIterative($root);
  17. if (!$root) return 0;
  18. if ($root->left == null && $root->right == null) return 1;
  19. if ($root->left == null) return $this->minDepth($root->right) + 1;
  20. if ($root->right == null) return $this->minDepth($root->left) + 1;
  21. return min($this->minDepth($root->left), $this->minDepth($root->right)) + 1;
  22. }
  23. function minDepthIterative($root) {
  24. if (!$root) return 0;
  25. $queue = [];
  26. array_push($queue, $root);
  27. $depth = 1;
  28. while (!empty($queue)) {
  29. foreach ($queue as $r) {
  30. if ($r->left == null && $r->right == null) return $depth;
  31. if ($r->left != null) array_push($queue, $r->left);
  32. if ($r->right != null) array_push($queue, $r->right);
  33. array_shift($queue);
  34. }
  35. ++$depth;
  36. }
  37. return -1;
  38. }
  39. }

GO代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func minDepth(root *TreeNode) int {
  10. if root == nil { return 0 }
  11. if root.Left == nil && root.Right == nil {
  12. return 1
  13. }
  14. if root.Left != nil && root.Right == nil {
  15. return minDepth(root.Left) + 1
  16. }
  17. if root.Right != nil && root.Left == nil {
  18. return minDepth(root.Right) + 1
  19. }
  20. return min(minDepth(root.Left), minDepth(root.Right)) + 1
  21. }
  22. func min(a, b int) int {
  23. if a < b {
  24. return a
  25. }
  26. return b
  27. }
  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func minDepth(root *TreeNode) int {
  10. depth := 0
  11. if root == nil {
  12. return depth
  13. }
  14. var queue []*TreeNode
  15. queue = append(queue, root)
  16. for len(queue) > 0 {
  17. qLen := len(queue)
  18. depth++
  19. for i := 0; i < qLen; i++ {
  20. if queue[i].Right == nil && queue[i].Left == nil {
  21. return depth
  22. }
  23. if queue[i].Left != nil {
  24. queue = append(queue, queue[i].Left)
  25. }
  26. if queue[i].Right != nil {
  27. queue = append(queue, queue[i].Right)
  28. }
  29. }
  30. queue = queue[qLen:]
  31. }
  32. return depth
  33. }