码迷,mamicode.com
首页 > 其他好文 > 详细

我也来刷LeetCode——0、Maximum Depth of Binary Tree(开篇)

时间:2015-08-25 16:21:40      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:

  作为一个非科班出身的程序员,还是很有必要刷刷题的。之前有个大牛说,菜鸟刷题可以从AC率高的刷起,这样可以快速培养信心。将LeetCode的题目按照AC率从高到低排序,第一道题目为 【Maximum Depth of Binary Tree】。

  从题目就可以看出,是求二叉树的最大深度。深度的概念,是指从根节点到叶子节点的这条路径上的总节点数。

  要求二叉树的最大深度,只需要求出左子树的深度和右子树的深度,取两者最大值再加 1 ,即为二叉树的最大深度。

  若该二叉树为空,返回 0 。

  然后就是将算法翻译成代码,很简单就有下面的答案:

1 if (root == NULL) 
2     return 0;
3 int leftDepth = maxDepth(root->left);
4 int rightDepth = maxDepth(root->right);
5 int max = leftDepth > rightDepth ? leftDepth : rightDepth;
6 return max + 1;

  我刷LeetCode另外还有个目的是为了顺便练习一下C++,所以用 STL 可以简化最后的代码:

1 if (root == NULL)
2     return 0;
3 return std::max(maxDepth(root->left), maxDepth(root->right)) + 1;

  这样看起来简洁多了,所以【Maximum Depth of Binary Tree】这道题完整的答案就是这样:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxDepth(TreeNode* root) {
13         if (root == NULL)
14             return 0;
15         return std::max(maxDepth(root->left), maxDepth(root->right)) + 1;
16     }
17 };

 

PS:《C++ Primer》里面有提到,在C++ 11里面,更推荐用 nullptr 来代替 NULL ,不过这里的原始数据结构就是 NULL , 所以用 NULL 了。

我也来刷LeetCode——0、Maximum Depth of Binary Tree(开篇)

标签:

原文地址:http://www.cnblogs.com/huangmingchuan/p/4757575.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!