二叉树的最小深度
来源:互联网 发布:java特种兵 下册 pdf 编辑:程序博客网 时间:2024/06/06 09:17
一、问题描述
给定一个二叉树,找出其最小深度。
二、样例
给出一棵如下的二叉树:
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 minDepth(TreeNode *root) {
if(root==NULL) return 0;
if(root->left==NULL&&root->right==NULL) return 1;
if(root->right==NULL) return minDepth(root->left)+1;
else if(root->left==NULL) return minDepth(root->right)+1;
else{
int d=minDepth(root->left)+1;
int e=minDepth(root->right)+1;
if(e>d) return d;
else return e;}
// write your code here
}
};
五、感悟
主要运用递归。
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 在xcode下用openssl写dh密钥交换,遇到“ld: library not found for -lcrypto”问题(已解决)
- bash脚本
- PAT-A-1088. Rational Arithmetic (20)
- linux系统用户免登设置
- 指针练习
- 二叉树的最小深度
- Eum 枚举类的学习
- 剑指offer--从上往下打印二叉树
- android studio查看函数用法、函数解释、函数说明
- 使用libcurl库实现SMTP发送邮件
- NAT的简介
- linux串口编程参数详解
- There is no Action mapped for namespace [/] and action name [employee_login] associated with context
- 二叉树