1.问题描述
给定一个二叉树,找出其最小深度。
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
2.解题思路
最小深度指的是第一个没有左节点和右节点的节点,只有一个分支的节点要找其分支中没有分支的节点,递归完所有的节点后,返回最小值。
3.代码实现
/**
* 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&&root->right==NULL)
return 1;
if(root->left==NULL)
{
return 1+minDepth(root->right);
}
else if(root->right==NULL)
{
return 1+minDepth(root->left);
}
else{
int leftDepth=minDepth(root->left)+1;
int rightDepth=minDepth(root->right)+1;
return leftDepth<rightDepth?leftDepth:rightDepth;
}
}
};
4.感想
注意递归思想的运用,以及返回条件的判断。