79:Maximum Depth of Binary Tree
2017-03-09 23:25
148 查看
题目: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:自底向上,代码如下:
解析2:自顶向下,代码如下:
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 Solution public: 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; } };
相关文章推荐
- [LeetCode OJ]Maximum Depth Of Binary Tree
- Maximum Depth of Binary Tree——Difficulty:Easy
- [Leetcode] Maximum depth of binary tree二叉树的最大深度
- leetcode 日经贴,Cpp code -Maximum Depth of Binary Tree
- [LeetCode]Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Leetcode - Maximum Depth of Binary Tree
- 迭代----- Maximum Depth of Binary Tree
- [LeetCode] Maximum Depth of Binary Tree
- LeetCode:Minimum Depth of Binary Tree,Maximum Depth of Binary Tree
- leetcode[104]Maximum Depth of Binary Tree
- Leetcode #104 Maximum Depth of Binary Tree
- 【Leetcode】Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree(leetcode)
- Maximum Depth of Binary Tree
- leetcode Maximum Depth of Binary Tree
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- Maximum Depth of Binary Tree
- leetcode 刷题之路 62 Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree