给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
-
思路分析:
求最大深度,用递归子问题处理,如果root为空,则深度为0,如果root不为空,则递归求出左子树的深度和右子树的深度,若左子树的深度小于右子树的深度,则返回右子树的深度+1,就为二叉树的最大深度,反之,则返回左子树的深度+1.
-
具体实现代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root) {
if(root==NULL)
{
return 0;
}
int leftDepth=maxDepth(root->left);
int rightDepth=maxDepth(root->right);
return leftDepth>rightDepth? leftDepth+1:rightDepth+1;
}