1、问题分析
题目链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
本质上就是一个二叉树的遍历问题。代码我已经进行了详细的注释,理解应该没有问题,读者可以作为参考,如果看不懂(可以多看几遍),欢迎留言哦!我看到会解答一下。
2、问题解决
笔者以C++
方式解决。
#include "iostream"
using namespace std;
#include "algorithm"
#include "vector"
#include "queue"
#include "set"
#include "map"
#include "cstring"
#include "stack"
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int maxDepth(TreeNode *root) {
return dealChen(root);
}
int dealChen(TreeNode *root) {
// 如果节点为空,则深度为0
if (root == NULL) {
return 0;
}
// 返回左子树和右子树种较大的深度,同时加上节点本身的深度
return max(dealChen(root->left), dealChen(root->right)) + 1;
}
};
int main() {
TreeNode *pNode1 = new TreeNode(3);
TreeNode *pNode2 = new TreeNode(9);
TreeNode *pNode3 = new TreeNode(20);
TreeNode *pNode4 = new TreeNode(15);
TreeNode *pNode5 = new TreeNode(7);
pNode1->left = pNode2;
pNode1->right = pNode3;
pNode3->left = pNode4;
pNode3->right = pNode5;
Solution *pSolution = new Solution;
int i = pSolution->maxDepth(pNode1);
cout << i << endl;
system("pause");
return 0;
}
运行结果
有点菜,有时间再优化一下。
3、总结
难得有时间刷一波LeetCode
, 这次做一个系统的记录,等以后复习的时候可以有章可循,同时也期待各位读者给出的建议。算法真的是一个照妖镜,原来感觉自己也还行吧,但是算法分分钟教你做人。前人栽树,后人乘凉。在学习算法的过程中,看了前辈的成果,受益匪浅。
感谢各位前辈的辛勤付出,让我们少走了很多的弯路!
哪怕只有一个人从我的博客受益,我也知足了。
点个赞再走呗!欢迎留言哦!