给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root) {
//树的最大深度为左子树与右子树深度中的最大值
int l_depth = 0, r_depth = 0;
if(root == NULL) return 0;
else{
l_depth = maxDepth(root -> left) + 1;
r_depth = maxDepth(root -> right) + 1;
}
int depth = (l_depth > r_depth) ? l_depth : r_depth;
return depth;
}

本文详细介绍了如何计算二叉树的最大深度,通过递归算法遍历左右子树,找到从根节点到最远叶子节点的最长路径上的节点数量。示例中使用了一个具体的二叉树结构进行演示。
3007

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



