题目:给定一个二叉树,找出其最大深度。
二叉树的深度,是指根节点到最远叶子节点的最长路径上的节点数,即所有结点层次的最大值。
思路:将每个节点所在层次数都判断出来,就能求出一棵二叉树的最大深度。这里使用后序递归遍历的方法求。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root)
{
int hl,hr,max;
if(root!=NULL)
{
hl=maxDepth(root->left);
hr=maxDepth(root->right);
max=hl>hr?hl:hr;
return max+1;
}
else
return 0;
}