一.题目:二叉树的最小深度
二.算法思想
直接递归,一定要注意比如如果结点无左结点而有右结点时,此时要看右子树的最小深度(注意加1),因为如果题目定义的是“根结点到最近的叶结点”,所以别误以为因为左子树为空所以此时深度为1。
如果左子树和右子树都不为空时,则返回左右子树的最小深度+1。
三.代码
/**
* 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) return 0;
if(!root->left) return minDepth(root->right)+1;
if(!root->right) return minDepth(root->left)+1;
return min(minDepth(root->right),minDepth(root->left))+1;
}
};