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.
题意为:输出一个二叉树的深度
实现起来很容易。Accepted
用C代码实现如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode *root) {
int LD,RD;
if(root==NULL)
return 0 ;
else{
LD = maxDepth(root->left); // 左子树的深度
RD = maxDepth(root->right); // 右子树的深度
return (LD>RD?LD:RD)+1; // 返回左、右子树深度的最大值+1,即整棵树的最大深度
}
}
本文介绍了一种使用递归方法来确定二叉树最大深度的算法,并提供了C语言的具体实现代码。该方法通过计算左右子树的深度并取较大者加一的方式得出整棵树的深度。

1365

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



