111. 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:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
题目链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
思路
递归思想的练习。非递归不写了。
相比求最大深度的题,本题多了一个小陷阱:深度代表的是从根节点出发到叶子节点结束。
特殊:[3,null,20,15,7],答案是3二不是1。
因此向上返回长度时,需要判断当前节点是否左右都有孩子,有则返回左右中较小深度,无则返回较大深度(较小值其实就是0)。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
int l = minDepth(root->left);
int r = minDepth(root->right);
if(root->left && root->right) return min(l,r)+1;
else return max(l,r)+1;
}
};