O(n)

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int max(int a,int b){
return a>b?a:b;
}
int maxDepth(struct TreeNode* root){
if(root==NULL){
return 0;
}
if(root->left==NULL&&root->right==NULL){
return 1;
}
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
本文介绍了一种计算二叉树最大深度的算法,使用递归方式遍历树的左子树和右子树,返回最大深度加一。文章包含了一个C语言实现的示例代码,展示了如何定义二叉树节点结构体以及max和maxDepth函数。
788

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



