79:Maximum Depth of Binary Tree
来源:互联网 发布:人工智能与装备制造业 编辑:程序博客网 时间:2024/06/06 06:53
题目: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:自底向上,代码如下:
// 递归法,时间复杂度 O(n),空间复杂度 O(logn)// 自底向上,从叶节点开始计算树的最大深度class Solution {public: int maxDepth(TreeNode* root) { if (!root) return 0; return max(maxDepth(root -> left), maxDepth(root -> right)) + 1; }};
解析2:自顶向下,代码如下:
// 迭代法,时间复杂度 O(N), 空间复杂度 O(logn)// 自顶向下,从根节点开始计算树的最大深度class Solutionpublic: int maxDepth(TreeNode* root) { if (!root) return 0; int result = 0; stack<pair<TreeNode*, int>> s; s.push(make_pair(root, 1)); while (!s.empty()) { auto p = s.top().first; auto depth = s.top().second; s.pop(); if (!p -> left && !p -> right) result = max(result, depth); if (p -> left) s.push(p -> left, depth + 1); if (p -> righth) s.push(p -> right, depth + 1); } return result; }};
0 0
- 79: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
- ubuntu16.04输入法使用,fcitx输入法配置
- css颜色和长度简写
- myeclipse中Package Explorer 里面的包的分布格式
- Flink-CEP之NFA
- 在fragment中实现返回键单击提醒 双击退出
- 79:Maximum Depth of Binary Tree
- Mac 应用列表(重装系列备用)
- JavaScript学习笔记
- 今天开始好好学习吧!
- 使用缓冲功能的BufferedReader和BufferedWriter复制文本文件,按照行读写
- 第一章 多线程的技能
- 时间、空间复杂度
- 你是我的小呀小cookie
- 大数据IMF传奇行动绝密课程第71课:Spark SQL窗口函数解密与实战