求二叉树的最大高度
1. 空树最大深度是0. 2. max(左子树的最大深度, 右子树最大深度) + 1
// 104. Maximum Depth of Binary Tree
// 1. 空树最大深度是0. 2. max(左子树的最大深度, 右子树最大深度) + 1
int solution::maxDepth(TreeNode* root)
{
if (root == NULL) return 0;
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
本文介绍了一种求解二叉树最大深度的递归算法。通过递归地计算左子树和右子树的最大深度,并取两者较大值加一得到整棵树的最大深度。适用于计算机科学中的数据结构学习。
398

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



