LeetCode (Maximum Depth of Binary Tree)
来源:互联网 发布:实物期权 知乎 编辑:程序博客网 时间:2024/06/06 12:39
Problem:
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.
Solution1:/** * 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; return 1 + max(maxDepth(root->left), maxDepth(root->right)); }};
Solution2:
/** * 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; int d = 0; queue<TreeNode*> q; q.push(root); while(!q.empty()){ int n = q.size(); for(int i = 0; i < n; i++){ TreeNode* p = q.front(); q.pop(); if(p->left) q.push(p->left); if(p->right) q.push(p->right); } d++; } return d; }};
阅读全文
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
- 74 C语言自定义函数
- Python的时间函数处理
- springmv 后台传给前台页面数据的4种方法
- 青年人,还有什么理由不顽强到底呢
- Linux
- LeetCode (Maximum Depth of Binary Tree)
- 函数实现的契约——线程安全与透明引用
- Redis中5种数据结构的使用场景介绍
- 牛腩——基础知识(一)
- linux创建并管理LVM分区
- win7系统没有桌面图标只有文字该怎么处理?
- 75 C语言函数的参数和返回值
- Nginx [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
- vue--v-model指令