104. Maximum Depth of Binary Tree
来源:互联网 发布:淘宝嘉贝逸飞旗舰店 编辑:程序博客网 时间:2024/06/05 19:58
1.Question
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.
2.Code/** * 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 == NULL) return 0; int left_depth = maxDepth(root->left), right_depth = maxDepth(root->right);if(left_depth >= right_depth)return left_depth + 1;elsereturn right_depth + 1; }};
3.Note
a. 对于树,就要想到递归。本题思想是,返回左右子树中最大深度,通过递归来实现。
b.最初版本
class Solution {public: int maxDepth(TreeNode* root) { if(root == NULL) return 0;if(maxDepth(root->left) >= maxDepth(root->right))return maxDepth(root->left) + 1;elsereturn maxDepth(root->right) + 1; }};
以上这个版本是第一次写的版本,出现了 Time limited exceed。 然后参考了别人的时候发现,我的算法的缺点在于:在比较时算了两遍maxDepth(),比较完大小之后,return 语句中又算了一遍maxDepth()。这没必要。所以可以考虑另外定义一个变量名来保存maxDepth() 的结果。
c.更简洁版本
class Solution {public: int maxDepth(TreeNode* root) { if(root == NULL) return 0;else return max(maxDepth(root->left),maxDepth(root->right)) + 1; }};
这个是最后想到的,更简洁的版本,通过调用max()函数来简化代码。两行即可搞定。
0 0
- [LeetCode]104.Maximum Depth of Binary Tree
- 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
- 104. Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- leetCode 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 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
- block 使用__weak 和__strong修饰符问题
- 设计模式——观察者模式
- Android避免按钮被用户快速多次点击(setEnabled的使用)
- java抽象类和接口区别
- 升级hibernate>4,spring>3.1笔记
- 104. Maximum Depth of Binary Tree
- JLINK-v8不亮灯刷固件教程
- 最新可访问Google的Hosts文件
- 原子变量AtomicLong
- Python面向对象学习(3):
- Android中Service服务详解(一)
- DWR 学习及深入
- 格式化输出--%m.n
- 安装HomeBlew