Given a binary tree, find its maximum depth.
这到题最容易想出的方法是递归
递归就是自己调用自己,数的子树又是数,一个二叉树的深度是左子树和右子树中深度最大的加上一;
递归还必须有出口,当树不为空才符合上面,所以出口是根节点为空
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root) {
int lchild,rchild;
if(root == NULL)
{
return 0;
}
lchild = maxDepth(root->left);
rchild = maxDepth(root->right);
return lchild>rchild?1+lchild:1+rchild;
}