给定一个二叉树 root
,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:3
示例 2:
输入:root = [1,null,2] 输出:2
提示:
- 树中节点的数量在
[0, 104]
区间内。 -100 <= Node.val <= 100
【分析】
求二叉树的最大深度,可通过深度优先遍历来遍历左右子树的最大深度,然后将左右子树的最大深度+1即可。(加上根节点的高度)需要排除树为空的情况。
具体案例分析:
输入:root=[3,9,20,null,null,15,7],输出:3
root=3,不为空,进行判断左和右子树。调用
ldepth=maxDepth(root->left)来判断左子树,此时根9。左右子树均为空,左子树不大于右子树,执行return right+1,为1。
调用
rdepth=maxDepth(root->right)调用来判断右子树,此时根为20,均有左右子树,且左子树不大于右子树执行return right+1,为1,然后继续调用函数,分别判断左和右子树。调用
ldepth=maxDepth(root->left)来判断左子树,此时根15。左右子树均为空,左子树不大于右子树,执行return right+1,为2。调用
rdepth=maxDepth(root->right)调用来判断右子树,此时根为7,左右子树均为空,左子树不大于右子树,执行return right+1,为2。调用结束,此时左为1,右为2,执行return right+1,为3。最后结果为3。
C语言具体代码如下:
/**
* 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;
}
else{
int ldepth=maxDepth(root->left);
int rdepth=maxDepth(root->right);
if(ldepth>rdepth){
return ldepth+1;
}else{
return rdepth+1;
}
}
}
时间复杂度O(n);空间复杂度O(height)