Easy 104题 Maximum Depth of Binary Tree
来源:互联网 发布:node express restful 编辑:程序博客网 时间:2024/06/05 01:04
问题: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.
又是一道有思路的题,直接写出答案,但是由于太不考虑复杂度了,报了time limited的错,改一下就好,但同样不是最优美的代码,看了discuss,发现有一行解决的!
以下这个代码的思路是DFS的,深度遍历。。。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxDepth(TreeNode* root) { if(!root) return 0; else { //return maxDepth(root->left)>maxDepth(root->right)?maxDepth(root->left)+1:maxDepth(root->right)+1; //算了多少遍。。复杂度太差 int l=maxDepth(root->left); int r=maxDepth(root->right); return l>r?l+1:r+1; //return 1 + max(maxDepth(root->left), maxDepth(root->right)); //一行解决 } }};
很自然想到应该还有BFS算法,引入队列?队列核心:first in first out 但是基本功太差。。啊先睡觉明儿早补
http://blueve.me/archives/417 这篇让我入门了。。
BFS复杂度更好些,因为没有递归。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxDepth(TreeNode* root) { //BFS if(!root) return 0; queue<TreeNode*> q; q.push(root); int count=1; //记录当前层数有多少元素 int depth=0; while(!q.empty()) { TreeNode* tmp=q.front(); q.pop(); //一一弹出当前层的元素 count--; if(tmp->left) q.push(tmp->left); if(tmp->right) q.push(tmp->right); if(count==0) { depth++; count=q.size(); } } return depth; }};
0 0
- Easy 104题 Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree(easy)
- 104. Maximum Depth of Binary Tree (Easy)
- [Leetcode 104, Easy] Minimum (Maximum) Depth of Binary Tree
- 【LeetCode】(104)Maximum Depth of Binary Tree(Easy)
- LeetCode #104 - Maximum Depth of Binary Tree - Easy
- 【Leetcode-easy-104】Maximum Depth of Binary Tree
- 【leetcode】【Easy】【104. Maximum Depth of Binary Tree】【tree】
- Leetcode----104. Maximum Depth of Binary Tree(easy)
- 104. Maximum Depth of Binary Tree [easy] (Python)
- Easy-题目3:104. Maximum Depth of Binary Tree
- Leetcode 104. Maximum Depth of Binary Tree (Easy) (cpp)
- LeetCode解题报告 104. Maximum Depth of Binary Tree [easy]
- Maximum Depth of Binary Tree——Difficulty:Easy
- LeetCode-Easy刷题(21) Maximum Depth of Binary Tree
- Leetcode 104 Maximum Depth of Binary Tree
- LeetCode(104)Maximum Depth of Binary Tree
- LeetCode 104 Maximum Depth of Binary Tree
- 华为OJ 初级:蛇形矩阵
- 设计模式(二)建造者模式
- 线程和进程
- pjsip学习笔记之一 –pjsip库编译及使用
- UVALive 6621 Pocket Cube(暴力)
- Easy 104题 Maximum Depth of Binary Tree
- CodeForces 589B Layer Cake
- 详解HttpURLConnection
- 关于TCP ,select,epoll服务器的区别与联系
- Codeforces Beta Round #5
- UVALive 6620 Josephina and RPG(概率DP)
- 2015上海EC-Fianl比赛总结
- Aizu - 2224
- .net 验证码