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;
}
}