Maximum Depth of Binary Tree
来源:互联网 发布:知乎 印度军工 编辑:程序博客网 时间:2024/06/05 22:31
题目104:Maximum 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.
思路分析:
和求二叉树的最小深度类似的解法类似,有递归和非递归两种解法。
1. 递归解法
class Solution {public: int maxDepth(TreeNode* root) { if (0 == root) return 0; return 1 + max(maxDepth(root->left), maxDepth(root->right)); }};
2. 非递归解法
思路分析:
二叉树的层次遍历,一直遍历到最后一个结点,此时的深度就是求的深度。
class Solution {public: int maxDepth(TreeNode* root) { if (0 == root) return 0; queue<TreeNode *> que; int depth, i, len; que.push(root); depth = 1; while (!que.empty()) { len = que.size(); for (i = 0; i < len; i ++) { TreeNode *qtop = que.front(); que.pop(); if (qtop->left) que.push(qtop->left); if (qtop->right) que.push(qtop->right); } if (que.empty()) return depth; ++ depth; } }};
while里面有for循环,还要优化的地方。
用cuc_num统计当前层的结点个数,next_num统计下一层的结点个数。
class Solution {public: int maxDepth(TreeNode* root) { if (0 == root) return 0; queue<TreeNode *> que; int cur_num, next_num, depth; que.push(root); depth = 1; cur_num = 1; next_num = 0; while (!que.empty()) { TreeNode *qtop = que.front(); que.pop(); -- cur_num; if (qtop->left) { que.push(qtop->left); ++ next_num; } if (qtop->right) { que.push(qtop->right); ++ next_num; } /* 判断队列是否为空,如果为空,深度不再需要加1 */ if (!que.empty() && 0 == cur_num) { cur_num = next_num; next_num = 0; ++ depth; } } return depth; }};
0 0
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- 路由器的原理及其配置(一)
- SpringMvc参数的传递(传值)
- 关于SQL Server 默认连接选项二三事
- matlab通过摄像头获取图像进行处理
- node_modules文件夹路径太长无法删除
- Maximum Depth of Binary Tree
- C++中public,protected,private访问小结
- 欢迎使用CSDN-markdown编辑器
- String和StringBuffer的equals方法比较
- 系统函数C字符串的实现(7):wcsrev
- 路由器的原理及其配置(二)
- 九度oj 1041
- zoj 3201 Tree of Tree 树形dp基础题——树形背包
- 创业之前你需要了解的九个真相