这题让计算二叉树的深度,如果节点为空,则深度为 0
,否则我们通过递归的方式分别计算左子树和右子树的深度,那么二叉树的最大深度就是取两个子树的最大深度加 1
,这个 1
就是当前节点贡献的深度,如下图所示:
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
// 递归,取左右子树的最大深度加 1 。
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
public:
int maxDepth(TreeNode *root) {
if (root == nullptr)
return 0;
// 递归,取左右子树的最大深度加 1 。
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}