LeetCode 104. Maximum Depth of Binary Tree (C++)
来源:互联网 发布:淘宝店运营方案论文 编辑:程序博客网 时间:2024/06/05 03:41
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.
方法一: 深度优先遍历
/** * 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 maxLvl = 0; dfs(root, maxLvl, 0); return maxLvl; } void dfs(TreeNode* root, int& max, int level) { if(!root) return; if(level+1 > max) max = level+1; dfs(root->left, max, level+1); dfs(root->right, max, level+1); }};
方法二:广度优先遍历, 用一个queue也可以做到分层遍历。
class Solution {public: int maxDepth(TreeNode* root) { if(!root) return 0; int maxlvl = 0; queue<TreeNode*> nQueue; nQueue.push(root); while (!nQueue.empty()) { ++maxlvl; for(int i=0, n=nQueue.size(); i < n; ++i) { TreeNode* cur = nQueue.front(); nQueue.pop(); if (cur->left) nQueue.push(cur->left); if (cur->right) nQueue.push(cur->right); } } return maxlvl; }};
阅读全文
0 0
- [C]LeetCode:Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree C语言
- Leetcode-104. Maximum Depth of Binary Tree c语言
- LeetCode 104. Maximum Depth of Binary Tree 题解(C++)
- LeetCode 104. Maximum Depth of Binary Tree (C++)
- [LeetCode] [C] 104. 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
- LeetCode --- 104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- leetCode 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree LeetCode
- 104. Maximum Depth of Binary Tree LeetCode
- LeetCode 104. 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
- c语言字符转换
- 对象与对象引用
- 矩阵乘法计算量估算
- Servlet中获得转发对象(RequestDispatcher)
- npm常用命令总结
- LeetCode 104. Maximum Depth of Binary Tree (C++)
- python使用技巧1
- 函数调用栈
- HBase 总结(五)
- 分布式与集群
- CSS3 2 2D 3D转换
- JDBC连接池&DBUtils
- jquery对象数值步进显示效果
- 获取post请求的数据