LeetCode 104.Maximum Depth of Binary Tree 解题报告
题目描述
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.
示例
上面的二叉树中最大深度是5,路径为从A到
限制条件
没有明确给出。
解题思路
二叉树是天然很适合递归的一种数据结构,所以自然而然会考虑使用递归的算法。求一个二叉树的最大深度,可以分解为求左右子树中的最大深度值再加1,对于子树而已,同样可以如此分解,所以递归的过程就是求左右子树的最大深度值,递归的结束条件是当没有子树时,返回深度值0。
代码
/**
* 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 == nullptr)
return 0;
else
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
总结
这道题涉及到二叉树,如果是求二叉树的最大深度,最小路径和之类的问题,一般可以考虑一下递归算法。好久没有复习二叉树相关的知识,得趁着做题的机会复习一下。
一天至少填一坑,坚持坚持,加油~