一.题目描述
给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
样例
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
与求最大深度的思想差不多,利用递归的方法求两棵子树的深度,比较后返回小的一个+1.
三.实现代码
/**
* 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 false;
if(root->left==NULL) return minDepth(root->right)+1;
if(root->right==NULL) return minDepth(root->left)+1;
int leftdepth=minDepth(root->left);
int rightdepth=minDepth(root->right);
if(leftdepth>rightdepth) return rightdepth+1;
else return leftdepth+1;
}
};
四.感悟
/**
* 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 false;
if(root->left==NULL) return minDepth(root->right)+1;
if(root->right==NULL) return minDepth(root->left)+1;
int leftdepth=minDepth(root->left);
int rightdepth=minDepth(root->right);
if(leftdepth>rightdepth) return rightdepth+1;
else return leftdepth+1;
}
};
一开始我就直接按照求二叉树最大深度的代码写上了,结果是wrong answer,这道题需要考虑左右子树为空的情况.