leetcode Maximum Depth of Binary Tree
来源:互联网 发布:pscs3软件百度云 编辑:程序博客网 时间:2024/06/08 05:57
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.
统计二叉树的最大深度,分为BFS,和DFS
BFS思路:
思路最重要,有了思路才有代码。
1.每次遍历一层,把这层所有的节点遍历完。
2.把这层所有的左右子树依次压入队列。
3.这层遍历完后,把这层所有的根节点pop出来。进入下一层节点,即步骤2中新压入的节点。
4.再遍历2中的所有节点,遍历完后,pop
/** * 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) { int deepth=0; if (root ==NULL) return 0; queue<TreeNode *> dequeTree; dequeTree.push(root); while(!dequeTree.empty()){ deepth++; for(int i=0,n=dequeTree.size();i<n;i++){ TreeNode *p =dequeTree.front(); dequeTree.pop(); if(p->left!=NULL) dequeTree.push(p->left); if(p->right!=NULL) dequeTree.push(p->right); } } return deepth; }};
DFS 思路:
一直向下搜索,直到搜索到叶子时才返回。意味着每个分支都要被遍历和比较。
class Solution {public: int maxDepth(TreeNode* root) { if (root ==NULL) return 0; return max(maxDepth(root->left),maxDepth(root->right))+1; }};
0 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
- sourcetree 无法提交代码
- Retrofit2.0 和Instant Run 冲突导致 java.lang.ArrayIndexOutOfBoundsException
- C语言学习3
- tolua++ lib 和 exe的生成
- String类型出生年月计算年龄
- leetcode Maximum Depth of Binary Tree
- poj 2632 Crashing Robots
- EventBus源代码深度剖析
- springmvc图片上传到虚拟目录
- java web和Android第一次交互(登录)
- jenkins中jelly文件的使用
- Android ImageView的scaleType属性与adjustViewBounds属性
- CSU1513 Kick the ball! 湖南10届省赛 dfs
- SIFT特征提取分析