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.
class Solution
{
public:
int maxDepth(TreeNode *root)
{
int nDepth,nLeftDep,nRightDep;
if (root == NULL)//如果根节点为空则返回0
return 0;
if (root->left == NULL&&root->right == NULL)//如果根节点的左右子树都是空则返回1
return 1;
nLeftDep = maxDepth(root->left);
nRightDep = maxDepth(root->right);
nDepth = nLeftDep > nRightDep ? nLeftDep : nRightDep;//比较左右子树返回的最大深度,取较大的
return nDepth + 1;
}
};