作为一个非科班出身的程序员,还是很有必要刷刷题的。之前有个大牛说,菜鸟刷题可以从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 了。
时间: 2024-08-26 02:54:10