Minimum Depth of Binary Tree
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 1:
Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5
Constraints:
The number of nodes in the tree is in the range [0, 105].
-1000 <= Node.val <= 1000
思路一:假设给定的节点不为空,那么完全分类后有四种情况
- left == null && right == null
- left != null && right != null
- left == null && right != null
- left != null && right == null
其中只有第一种情况是符合题目的叶子节点,递归判断即可
public int minDepth(TreeNode root) {
if (root == null) return 0;
return minDepth(root, 1);
}
public int minDepth(TreeNode root, int depth) {
if (root.left == null && root.right == null) {
return depth;
} else if (root.left != null && root.right == null) {
return minDepth(root.left, depth + 1);
} else if (root.right != null && root.left == null) {
return minDepth(root.right, depth + 1);
} else {
return Math.min(minDepth(root.left, depth + 1), minDepth(root.right, depth + 1));
}
}
思路二:官方给的题解是从底层往上递归,代码可以更简洁
标签:right,depth,minDepth,111,easy,null,root,leetcode,left From: https://www.cnblogs.com/iyiluo/p/16939842.html