Maximum Depth of Binary Tree
2015-10-20 19:52
295 查看
题目:Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.思路:深搜
如果节点为空,返回0,;如果不为空,要看是否左右孩子节点是否存在,不存在直接返回1.然后剩下有说明至少存在一个,左节点在,就定义left加上1.右节点同样处理。
代码:
/*** Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//本质上方法一样,只是通过实践竟然不同
class Solution1 {
//https://leetcode.com/problems/maximum-depth-of-binary-tree/
public:
int maxDepth(TreeNode* root) {
if(root==NULL){
return 0;
}
if(root->left==NULL&&root->right==NULL){
return 1;
}
int left=0;
if(root->left){
left=maxDepth(root->left)+1;
}
int right=0;
if(root->right){
right=maxDepth(root->right)+1;
}
return max(left,right);
}
};
class Solution2 {
public:
int count=1;
int maxDepth(TreeNode* root) {
if(root==NULL){
return 0;
}
//int left=maxDepth(root->left);
//int right=maxDepth(root->right);
return max(maxDepth(root->left)+1,maxDepth(root->right)+1);
}
};
相关文章推荐
- 私房库视频学习笔记-小清新BBS系统开发技术归纳三
- 将 nginx 安装成 windows 的方法
- 做不了诗人,也可以吟唱美好
- eclipse/myeclipse遇到的问题及解决方法
- 实现基础计算器--Basic Calculator
- 使用secureCrt端口转发连接远程服务器mysql
- Minimum Depth of Binary Tree
- Android第三方开源ImageLoader的使用(一)
- 设计模式之一 设计模式概述
- 爬爬爬之路:C语言(九) 结构体指针与预编译指令
- Java 8.1
- c++数组访问越界的问题
- jquery的ajax
- ios开发之c语言基础-结构体
- android 随机云标签(圆形)
- 内存映射文件 进程间通讯
- DELPHI 让子窗体显示在任务栏上
- HBase深入学习笔记
- 参加某项目例会小记-2015-10-20
- 如何访问到静态的文件,如jpg,js,css?