leetcode笔记:Maximum Depth of Binary Tree
2015-10-17 23:12
369 查看
一. 题目描述
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.
二. 题目分析
这道题和Minimum Depth of Binary Tree一题相似,这个是求最大深度的,就是对二叉树进行递归,然后将子树的最大深度进行返回,最终得到这个树的最大深度。
这个方法的时间复杂度为:
三. 示例代码
四. 小结
无。
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.
二. 题目分析
这道题和Minimum Depth of Binary Tree一题相似,这个是求最大深度的,就是对二叉树进行递归,然后将子树的最大深度进行返回,最终得到这个树的最大深度。
这个方法的时间复杂度为:
O(n),空间复杂度为:
O(logn)。
三. 示例代码
// 时间复杂度为O(n),空间复杂度O(logn) struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int maxDepth(TreeNode* root) { if (!root) { return 0; } int Result = 1; int Left = maxDepth(root->left); int Right = maxDepth(root->right); if (Left * Right) { Result += Left < Right? Right : Left; } else { Result += Right + Left; } return Result; } };
四. 小结
无。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- AVL树-自平衡二叉查找树(Java实现)
- c++ primer 第五版 笔记前言
- 命令行快速技巧:如何定位一个文件
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- jquery+CSS实现的多级竖向展开树形TRee菜单效果
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例