二叉树的最大深度
来源:互联网 发布:mplayerx mac dmg 编辑:程序博客网 时间:2024/05/03 02:01
1.问题描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
样例给出一棵如下的二叉树:
1 / \ 2 3 / \ 4 5
这个二叉树的最大深度为3
.
2.解题思路
如果二叉树为空,则深度为0;如果不为空,运用递归,分别求其左子树和右子树的深度,取最大的再加1,因为根节点深度是1,要加进去。
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 maxDepth(TreeNode *root) {
// write your code here
if(root==NULL)
return 0;
int leftDepth=maxDepth(root->left)+1;
int rightDepth=maxDepth(root->right)+1;
return leftDepth>rightDepth?leftDepth:rightDepth;
}
};
4.感想
注意递归是解决二叉树的重要方法,当子问题与原问题一样且子问题小于原问题时考虑用递归。
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- 二叉树的最大深度
- Linux 限制SFTP用户只能访问某个目录
- Tensorflow实例-CNN处理句子相似度(下)
- Java复习-并发编程之synchronized
- 51nod 1019逆序数
- swwd
- 二叉树的最大深度
- BaseAdapter简单封装
- View工作原理(一)事件传递原理详解
- 2016蓝桥杯省赛 快速排序
- 冒泡排序算法
- 算法导论 练习题 6.5-8
- 欢迎使用CSDN-markdown编辑器
- 五 串(未完工)
- 制作tab中遇到的jq问题