lintcode——二叉树的最小深度
2017-04-07 23:59
369 查看
1.题目
给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
样例
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
2.思路
先考虑空树,返回0;
考虑是否为左右斜树,则直接递归求深度即可;
考虑非空树时,递归,在回溯过程中不断比较左右子树深度,每次取较小深度,继续回溯……
同最大深度一样,不要忘了加上根节点!!
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) //右斜树
return minDepth(root->right)+1;
if(root->right==NULL) //左斜树
return minDepth(root->left)+1;
int leftlen=minDepth(root->left); //非斜树
int rightlen=minDepth(root->right); //非斜树
return min(leftlen,rightlen)+1; //非斜树
}
};
4.感想
觉得自己还是要区分好最小深度和最大深度,不能单纯地使用递归。因为二叉树的深度必须是根结点到叶子结点的距离,不能单纯的比较左右子树的递归结果返回较小值,因为对于有单个孩子为空的节点,为空的孩子会返回0,但这个节点并非叶子节点,故返回的结果是错误的。
之所以自己会在遍历和求深度的题目上有许多问题是因为对于递归的过程掌握的不够透彻!!希望自己通过做题找出理解上的薄弱点真正掌握递归,很多问题也就迎刃而解了!
1.题目
给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
样例
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
2.思路
先考虑空树,返回0;
考虑是否为左右斜树,则直接递归求深度即可;
考虑非空树时,递归,在回溯过程中不断比较左右子树深度,每次取较小深度,继续回溯……
同最大深度一样,不要忘了加上根节点!!
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) //右斜树
return minDepth(root->right)+1;
if(root->right==NULL) //左斜树
return minDepth(root->left)+1;
int leftlen=minDepth(root->left); //非斜树
int rightlen=minDepth(root->right); //非斜树
return min(leftlen,rightlen)+1; //非斜树
}
};
4.感想
觉得自己还是要区分好最小深度和最大深度,不能单纯地使用递归。因为二叉树的深度必须是根结点到叶子结点的距离,不能单纯的比较左右子树的递归结果返回较小值,因为对于有单个孩子为空的节点,为空的孩子会返回0,但这个节点并非叶子节点,故返回的结果是错误的。
之所以自己会在遍历和求深度的题目上有许多问题是因为对于递归的过程掌握的不够透彻!!希望自己通过做题找出理解上的薄弱点真正掌握递归,很多问题也就迎刃而解了!
相关文章推荐
- Lintcode---二叉树的最小深度
- lintcode-二叉树的最小深度-155
- LintCode:二叉树的最小深度
- lintcode--155. 二叉树的最小深度
- lintcode minimum-depth-of-binary-tree 二叉树最小深度
- lintcode : 二叉树的最小深度
- Lintcode-递归-97 二叉树的最大深度
- Lintcode---二叉树的最大深度
- lintcode 二叉树的最大深度
- lintcode :二叉树的最大深度
- lintcode maximum-depth-of-binary-tree 二叉树的最大深度
- LintCode:二叉树的最大深度
- lintcode&九章算法——No.97 二叉树的最大深度 ? 待解决
- lintcode——二叉树的最大深度
- LintCode-二叉树的最大深度
- lintcode binary-tree-maximum-path-sum 二叉树中的最大路径和
- 【LeetCode】Minimum Depth Of Binary Tree二叉树的最小深度 - Easy
- 求二叉树的最小深度
- 二叉树的最大深度与最小深度
- [LeetCode] 111. Minimum Depth of Binary Tree 二叉树的最小深度