題目:
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.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
分析:
查找二叉樹(shù)的最小深度
分2種情況:
如果結(jié)點(diǎn)為NULL,返回0
否則,返回1+左右結(jié)點(diǎn)的最小深度
但這里有個(gè)地方需要注意,如果左右結(jié)點(diǎn)有一個(gè)為空,則應(yīng)該返回1+另一個(gè)不為空的深度
如果左右節(jié)點(diǎn)都為空直接返回1
總結(jié)一下就是
if(l==0 || r==0)
return 1+l+r;
AC代碼
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root)
return 0;
int l = minDepth(root->left);
int r = minDepth(root->right);
if(l==0 || r==0)
return 1+l+r;
return 1+min(l,r);
}
};