题目:
给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
样例
/**
* 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 a=0,b=0;
int minDepth(TreeNode *root) {
// write your code here
int a=0,b=0;
if(root==NULL) return 0;
if(root->left==NULL&&root->right==NULL) return 1;
else if(root->left==NULL&&root->right!=NULL) {return b=minDepth(root->right)+1;}
else if(root->left!=NULL&&root->right==NULL) {return a=minDepth(root->left)+1;}
else{
a=minDepth(root->left)+1;
b=minDepth(root->right)+1;
if(a>=b) return b;
if(a<b) return a;
}
}
};
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
思路:
采用前序遍历的方法,每进入一层,将层数加一,最后返回左右子树中层数小的数。
具体代码:
* 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 a=0,b=0;
int minDepth(TreeNode *root) {
// write your code here
int a=0,b=0;
if(root==NULL) return 0;
if(root->left==NULL&&root->right==NULL) return 1;
else if(root->left==NULL&&root->right!=NULL) {return b=minDepth(root->right)+1;}
else if(root->left!=NULL&&root->right==NULL) {return a=minDepth(root->left)+1;}
else{
a=minDepth(root->left)+1;
b=minDepth(root->right)+1;
if(a>=b) return b;
if(a<b) return a;
}
}
};
感悟:
该题与二叉树的最大深度不同,该题还要复杂。要考虑很多细节,比如左右子树有一个为空时,该如何处理。