题目:
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.
解题思路:
当节点为空时,返回0,否则返回左右儿子中最深的深度值。
代码:
/**
* Definition for binary tree
* 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)return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
本文介绍了如何通过递归算法来解决寻找二叉树最大深度的问题。通过不断深入树的结构,找到从根节点到最远叶子节点的最长路径长度。
1383

被折叠的 条评论
为什么被折叠?



