Leetcode NO.104 Maximum Depth of Binary Tree
来源:互联网 发布:韩国tvn软件下载 编辑:程序博客网 时间:2024/06/08 01:17
题目要求如下:
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.
本题应该算是Leetcode里面最简单的题之一了。。就用单纯的dfs就可以做出,dfs()函数有两个参数,第二个就是储存当前的depth。如果找到了leaf node,此时depth大于之前的max,则替换max。。如果没有找到leaf node,则继续遍历,代码如下:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxDepth(TreeNode *root) { count = 0; if (root == NULL) return 0; dfs(root, 0); return count; }private: int count; void dfs(TreeNode* root, int depth) { if (root->left == NULL && root->right == NULL) { if (1 + depth > count) count = 1 + depth; } else { if (root->left != NULL) dfs(root->left, depth+1); if (root->right != NULL) dfs(root->right, depth+1); } }};
0 0
- Leetcode NO.104 Maximum Depth of Binary Tree
- LeetCode--No.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: Maximum Depth of Binary Tree [104]
- 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
- Leetcode---(104)Maximum Depth of Binary Tree
- leetcode-104-Maximum Depth of Binary Tree
- [Java] 对象的强, 软, 弱和虚引用
- 相同源代码的html文件在本地和服务器端被浏览器请求时,显示的效果不一样!!!
- 错误隐藏学习手记(四)
- ASPX EVAL函数的运用
- C#编程中(ASP.Net)获取当前网页路径的所有方法集合总结
- Leetcode NO.104 Maximum Depth of Binary Tree
- Codeforces Round #289 (Div. 2, ACM ICPC Rules) C题
- 自制操作系统 第3步
- [转]内容匹配广告投放技术
- 用来获取页面背景的书签(页面背景是DataURI)
- Insertion sort, select sort, Quick sort and Merge sort
- iOS复习笔记14:常用数据结构之类
- jquery 获取 自定义属性(attr 和 prop)
- ACM_switch case的使用