LeetCode题目笔记(二) -- Maximum Depth of Binary Tree
来源:互联网 发布:java后端开发技术架构 编辑:程序博客网 时间:2024/05/22 08:06
2. Problem: Maximum Depth of Binary Tree
Problem Description: 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.
Step I: Ask Questions
Complete binary tree? how is the binary tree implemented? What is depth?
Step II: Describe approaches to the problem-->Algorithm-->Algorithm Analysis.
与上一题相似,我们也有recursive和iterative的解法。
http://www.geeksforgeeks.org/write-a-c-program-to-find-the-maximum-depth-or-height-of-a-tree/
Iterative的解法还是用BFS。这一次找在queue里面的最后一个元素的depth值。两种方法的代码如下:
class Solution {public: int maxDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if( root == NULL ) return 0; if( root->left == NULL && root->right == NULL ) return 1; else return 1 + max( maxDepth( root->left ), maxDepth( root->right ) ); }};
class Solution {public:struct Node{ TreeNode *root; int depth; Node(TreeNode* n, int d):depth(d){ root = n; }}; int maxDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if( root==NULL ) return 0; queue<Node> q; q.push(Node( root, 1)); int maxDepth = 1; while( !q.empty() ) { Node u = q.front(); q.pop(); if( u.root->left ) q.push( Node(u.root->left, u.depth+1)); if( u.root->right ) q.push( Node(u.root->right, u.depth+1)); if( u.root->left==NULL && u.root->right == NULL) { if( maxDepth < u.depth ) maxDepth = u.depth; } } return maxDepth; }};
- LeetCode题目笔记(二) -- Maximum Depth of Binary Tree
- leetcode笔记:Maximum Depth of Binary Tree
- LeetCode算法题目:Maximum Depth of Binary Tree
- Leetcode - Tree - Maximum Depth of Binary Tree
- [leetcode][tree] 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 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
- Java开发中的23种设计模式详解
- hdu3065ac自动机
- rqnoj-21
- python操作Excel读写--使用xlrd
- hdu2896ac自动机
- LeetCode题目笔记(二) -- Maximum Depth of Binary Tree
- google-gson解析json数据---小实例
- 重温设计模式之开头篇
- 个人快捷键的总结
- 分享&交流&调查 xcode反汇编调试iOS模拟器程序
- 时间日期格式
- 驱动模块中Makefile的自我理解
- xcode反汇编调试iOS模拟器程序
- POJ 1042 Gone Fishing