111. Minimum Depth of Binary Tree
https://leetcode.com/problems/minimum-depth-of-binary-tree/
Description
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],
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
Solutions
这道树的最小高度让我想到之前做的树的最大高度。104. Maximum Depth of Binary Tree
那道是递归return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
所以,这里要求最小高度,不就是把左子树的最小高度和右子树的最小高度中较小的哪一个加一就行啦。
test case对了,交的时候WA。当inpu为[1,2]时,output是1,而expected是2。
因为根据定义,树的高度应该从根节点数起,而不是根节点。所以,当有一个子树为空时,应该计算另一个非空子树的高度,而不是得到min=0。
Submissions
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root==null)
return 0;
int left=minDepth(root.left);
int right=minDepth(root.right);
if(left==0)
return right+1;
if(right==0)
return left+1;
return Math.min(left,right)+1;
}
}
Summary
树的高度的定义。