给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
点题:和最大深度相比,需要注意的地方多一些
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param root: The root of binary tree
* @return: An integer
*/
int minDepth(TreeNode * root) {
// write your code here
if (root == NULL) {
return 0;
}
if (root->left == NULL) {
return minDepth(root->right) + 1;
} else if (root->right == NULL) {
return minDepth(root->left) + 1;
} else {
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
}
};