LeetCode Maximum Depth of Binary Tree
来源:互联网 发布:php引导页源码2017 编辑:程序博客网 时间:2024/05/29 04:18
1.题目描述
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.
2.解决方案1
class Solution {public: int maxDepth(TreeNode *root) { if(root == NULL){ return 0; } deque<TreeNode*> deqNodes; deqNodes.push_back(root); int depth = 0; int alreadyDoneCount = 1; while(deqNodes.empty() == false){ TreeNode* lastNode = deqNodes.back(); deqNodes.pop_back(); alreadyDoneCount--; if(lastNode->left){ deqNodes.push_front(lastNode->left); } if(lastNode->right){ deqNodes.push_front(lastNode->right); } if(alreadyDoneCount == 0){ ++depth; alreadyDoneCount = deqNodes.size(); } } return depth; }};
思路:采用宽度优先搜索,只有当添加的全处理了,树的深度才增加1,这个是个小技巧。
3.解决方案2
class Solution {public: int maxDepth(TreeNode *root) { if(root == NULL ){return 0;}else if(root != NULL && (root->left == NULL && root->right == NULL)){ return 1;}int leftTreeDepth = maxDepth(root->left);int rightTreeDepth = maxDepth(root->right);int maxDepth = leftTreeDepth > rightTreeDepth ? leftTreeDepth : rightTreeDepth;return maxDepth + 1; }};
思路:树的遍历当然可以用递归,但会比较慢。
http://www.waitingfy.com/archives/1586
2 0
- Leetcode - Tree - Maximum Depth of Binary Tree
- [leetcode][tree] Maximum Depth of Binary Tree
- LeetCode Maximum Depth of Binary Tree
- [Leetcode] Maximum Depth of Binary Tree
- leetcode 24: Maximum Depth of Binary Tree
- [LeetCode] Maximum Depth of Binary Tree
- Leetcode 104 Maximum Depth of Binary Tree
- 【leetcode】Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- [LeetCode]Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- Leetcode: Maximum Depth of Binary Tree
- LeetCode-Maximum Depth of Binary Tree
- [leetcode] Maximum Depth of Binary Tree
- LeetCode - Maximum Depth of Binary Tree
- LeetCode:Maximum Depth of Binary Tree
- LeetCode | Maximum Depth of Binary Tree
- 【leetcode】Maximum Depth of Binary Tree
- 【Java Web】 OGNL 与 Struts2.0 浅析
- LeetCode Wildcard Matching
- NET:Mail from must equal authorized user
- ReactiveCocoa -- Memory Management
- c++设计模式(享元模式)
- LeetCode Maximum Depth of Binary Tree
- select、poll、epoll之间的区别总结[整理]
- template模板类和模板函数
- C# 中使用 Excel
- 社説 20150306 18歳選挙権法案 高校の主権者教育を拡充せよ
- jsp导出Excel的简单方式 ContentType为Excel格式
- 4.3、函数参数和返回值
- 让自由职业更为便捷的35个工具和6个博客
- 虚函数及继承