LeetCode 104. Maximum Depth of Binary Tree
来源:互联网 发布:understand mac 编辑:程序博客网 时间:2024/06/04 19:18
104. Maximum Depth of Binary Tree
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.
Solution
- 题目意思就是求一二叉树的最大深度,空树的深度定义为0
- 我们可以采用递归的方式来进行,对于空树返回0,否则返回左子树深度+1和右子树深度+1的最大值。(因为子树的深度是父亲的+1)。代码如下:
class Solution {public: int maxDepth(TreeNode* root) { if (!root) return 0; else return max(maxDepth(root->left) + 1,maxDepth(root->right) + 1); }};
- 另外,上述方法其实是采用了DFS(深度优先搜索),在讨论区也看到了利用队列实现的BFS(广度优先搜索),代码如下,侵删。
int maxDepth(TreeNode *root){ if(root == NULL) return 0; int res = 0; queue<TreeNode *> q; q.push(root); while(!q.empty()) { ++ res; for(int i = 0, n = q.size(); i < n; ++ i) { TreeNode *p = q.front(); q.pop(); if(p -> left != NULL) q.push(p -> left); if(p -> right != NULL) q.push(p -> right); } } return res;}
阅读全文
0 0
- [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
- 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
- web服务端使用JSONArrayy或JSONObject转json字符串为Java对象或数组
- 1 Ubuntu系统下的CUDA安装与配置
- POJ 1583 Robot Motion(dfs+模拟)
- Linux命令笔记(未完成)
- using sap businessobjects predictive analytics with sap hana express edition
- LeetCode 104. Maximum Depth of Binary Tree
- Duplicate files copied in APK META-INF/DEPENDENCIES File
- JavaScript 之 Object.apply()与Object.call()和Object.bind()
- mui html5plus.ready事件
- 涉及到double 值比较的eps 应用
- eclipse下载及安装
- Android笔记(15)将bitmap存为文件
- STL内存管理器的分配策略
- 解决错误TypeError: data argument can't be an iterator