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,否则就计算其左子树和右子树的深度,总深度就是左右子树中深度大的那个再加1;
#include "stdafx.h"
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int maxDepth(struct TreeNode *root)
{
if(root == NULL)
return 0;
else
{
int l = maxDepth(root->left);
int r = maxDepth(root->right);
return (l > r ? l : r) + 1;
}
}
本文介绍了一种求解二叉树最大深度的递归算法。通过计算左右子树的最大深度来确定整棵树的最大深度,并提供了完整的C语言实现代码。
1407

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



