111. Minimum Depth of Binary Tree - Easy

﹏ヽ暗。殇╰゛Y 2021-09-20 12:52 333阅读 0赞

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

return its minimum depth = 2.

time: O(n), space: O(height)

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public int minDepth(TreeNode root) {
  12. if(root == null) {
  13. return 0;
  14. }
  15. if(root.left == null) {
  16. return minDepth(root.right) + 1;
  17. }
  18. if(root.right == null) {
  19. return minDepth(root.left) + 1;
  20. }
  21. return 1 + Math.min(minDepth(root.left), minDepth(root.right));
  22. }
  23. }

转载于:https://www.cnblogs.com/fatttcat/p/10197070.html

发表评论

表情:
评论列表 (有 0 条评论,333人围观)

还没有评论,来说两句吧...

相关阅读