【LeetCode】 Maximum Depth of Binary Tree
题目描述:
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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
解答:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root){
//该节点为空的情况
if(!root)
{
return 0;
}
//左子树为空、右子树不为空的情况:本节点加上右子树节点数
if(!root->left && root->right)
{
return (1 + maxDepth(root->right));
}
//右子树为空、左子树不为空的情况:本节点加上左子树节点数
if(root->left && !root->right)
{
return (1 + maxDepth(root->left));
}
//该节点不为空且没有左右子树即为叶子节点
if(!root->left && !root->right)
{
return 1;
}
//否则就将该节点的左右子树的节点算出来后取最大值与本节点数相加
int a = maxDepth(root->left);
int b = maxDepth(root->right);
return 1 + (a > b ? a : b);
}

浙公网安备 33010602011771号