0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

二叉树的最大深度

算法与数据结构 来源:代码随想录 作者:代码随想录 2022-07-26 11:28 次阅读

尽管之前你可能做过这道题目,但只要认真看完,相信你会收获满满!可以一起解决如下两道题目:

  • 104.二叉树的最大深度
  • 559.n叉树的最大深度

104.二叉树的最大深度

题目地址:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:给定二叉树 [3,9,20,null,null,15,7],

7b9b835a-0c92-11ed-ba43-dac502259ad0.png

返回它的最大深度 3 。

递归法

本题可以使用前序(中左右),也可以使用后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度。

而根节点的高度就是二叉树的最大深度,所以本题中我们通过后序求的根节点高度来求的二叉树最大深度。

这一点其实是很多同学没有想清楚的,很多题解同样没有讲清楚。

我先用后序遍历(左右中)来计算树的高度。

  1. 确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度,所以返回值为int类型。

代码如下:

intgetdepth(treenode*node)
  1. 确定终止条件:如果为空节点的话,就返回0,表示高度为0。

代码如下:

if(node==null)return0;
  1. 确定单层递归的逻辑:先求它的左子树的深度,再求的右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度。

代码如下:

intleftdepth=getdepth(node->left);//左
intrightdepth=getdepth(node->right);//右
intdepth=1+max(leftdepth,rightdepth);//中
returndepth;

所以整体c++代码如下:

classsolution{
public:
intgetdepth(treenode*node){
if(node==null)return0;
intleftdepth=getdepth(node->left);//左
intrightdepth=getdepth(node->right);//右
intdepth=1+max(leftdepth,rightdepth);//中
returndepth;
}
intmaxdepth(treenode*root){
returngetdepth(root);
}
};

代码精简之后c++代码如下:

classsolution{
public:
intmaxdepth(treenode*root){
if(root==null)return0;
return1+max(maxdepth(root->left),maxdepth(root->right));
}
};

精简之后的代码根本看不出是哪种遍历方式,也看不出递归三部曲的步骤,所以如果对二叉树的操作还不熟练,尽量不要直接照着精简代码来学。

本题当然也可以使用前序,代码如下:(充分表现出求深度回溯的过程)

classsolution{
public:
intresult;
voidgetdepth(treenode*node,intdepth){
result=depth>result?depth:result;//中

if(node->left==null&&node->right==null)return;

if(node->left){//左
depth++;//深度+1
getdepth(node->left,depth);
depth--;//回溯,深度-1
}
if(node->right){//右
depth++;//深度+1
getdepth(node->right,depth);
depth--;//回溯,深度-1
}
return;
}
intmaxdepth(treenode*root){
result=0;
if(root==0)returnresult;
getdepth(root,1);
returnresult;
}
};

可以看出使用了前序(中左右)的遍历顺序,这才是真正求深度的逻辑!

注意以上代码是为了把细节体现出来,简化一下代码如下:

classsolution{
public:
intresult;
voidgetdepth(treenode*node,intdepth){
result=depth>result?depth:result;//中
if(node->left==null&&node->right==null)return;
if(node->left){//左
getdepth(node->left,depth+1);
}
if(node->right){//右
getdepth(node->right,depth+1);
}
return;
}
intmaxdepth(treenode*root){
result=0;
if(root==0)returnresult;
getdepth(root,1);
returnresult;
}
};

迭代法

使用迭代法的话,使用层序遍历是最为合适的,因为最大的深度就是二叉树的层数,和层序遍历的方式极其吻合。

在二叉树中,一层一层的来遍历二叉树,记录一下遍历的层数就是二叉树的深度,如图所示:

7bb59e02-0c92-11ed-ba43-dac502259ad0.png

所以这道题的迭代法就是一道模板题,可以使用二叉树层序遍历的模板来解决的。

如果对层序遍历还不清楚的话,可以看这篇:二叉树:层序遍历登场!

c++代码如下:

classsolution{
public:
intmaxdepth(treenode*root){
if(root==null)return0;
intdepth=0;
queueque;
que.push(root);
while(!que.empty()){
intsize=que.size();
depth++;//记录深度
for(inti=0;i< size; i++) {
                treenode* node = que.front();
                que.pop();
                if(node->left)que.push(node->left);
if(node->right)que.push(node->right);
}
}
returndepth;
}
};

那么我们可以顺便解决一下n叉树的最大深度问题

559.n叉树的最大深度

题目地址:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/

给定一个 n 叉树,找到其最大深度。

最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

例如,给定一个 3叉树 :

7bc4f44c-0c92-11ed-ba43-dac502259ad0.png

我们应返回其最大深度,3。

思路:

依然可以提供递归法和迭代法,来解决这个问题,思路是和二叉树思路一样的,直接给出代码如下:

递归法

c++代码:

classsolution{
public:
intmaxdepth(node*root){
if(root==0)return0;
intdepth=0;
for(inti=0;i< root->children.size();i++){
depth=max(depth,maxdepth(root->children[i]));
}
returndepth+1;
}
};

迭代法

依然是层序遍历,代码如下:

classsolution{
public:
intmaxdepth(node*root){
queueque;
if(root!=null)que.push(root);
intdepth=0;
while(!que.empty()){
intsize=que.size();
depth++;//记录深度
for(inti=0;i< size; i++) {
                node* node = que.front();
                que.pop();
                for(intj=0;j< node->children.size();j++){
if(node->children[j])que.push(node->children[j]);
}
}
}
returndepth;
}
};

其他语言版本

java

104.二叉树的最大深度

classsolution{
/**
*递归法
*/
publicintmaxdepth(treenoderoot){
if(root==null){
return0;
}
intleftdepth=maxdepth(root.left);
intrightdepth=maxdepth(root.right);
returnmath.max(leftdepth,rightdepth)+1;

}
}
classsolution{
/**
*迭代法,使用层序遍历
*/
publicintmaxdepth(treenoderoot){
if(root==null){
return0;
}
dequedeque=newlinkedlist<>();
deque.offer(root);
intdepth=0;
while(!deque.isempty()){
intsize=deque.size();
depth++;
for(inti=0;i< size; i++) {
                treenode poll = deque.poll();
                if(poll.left!=null){
deque.offer(poll.left);
}
if(poll.right!=null){
deque.offer(poll.right);
}
}
}
returndepth;
}
}

python

104.二叉树的最大深度

递归法:

classsolution:
defmaxdepth(self,root:treenode)->int:
returnself.getdepth(root)

defgetdepth(self,node):
ifnotnode:
return0
leftdepth=self.getdepth(node.left)#左
rightdepth=self.getdepth(node.right)#右
depth=1+max(leftdepth,rightdepth)#中
returndepth

递归法:精简代码

classsolution:
defmaxdepth(self,root:treenode)->int:
ifnotroot:
return0
return1+max(self.maxdepth(root.left),self.maxdepth(root.right))

迭代法:

importcollections
classsolution:
defmaxdepth(self,root:treenode)->int:
ifnotroot:
return0
depth=0#记录深度
queue=collections.deque()
queue.append(root)
whilequeue:
size=len(queue)
depth+=1
foriinrange(size):
node=queue.popleft()
ifnode.left:
queue.append(node.left)
ifnode.right:
queue.append(node.right)
returndepth

559.n叉树的最大深度

递归法:

classsolution:
defmaxdepth(self,root:'node')->int:
ifnotroot:
return0
depth=0
foriinrange(len(root.children)):
depth=max(depth,self.maxdepth(root.children[i]))
returndepth+1

迭代法:

importcollections
classsolution:
defmaxdepth(self,root:'node')->int:
queue=collections.deque()
ifroot:
queue.append(root)
depth=0#记录深度
whilequeue:
size=len(queue)
depth+=1
foriinrange(size):
node=queue.popleft()
forjinrange(len(node.children)):
ifnode.children[j]:
queue.append(node.children[j])
returndepth

使用栈来模拟后序遍历依然可以

classsolution:
defmaxdepth(self,root:'node')->int:
st=[]
ifroot:
st.append(root)
depth=0
result=0
whilest:
node=st.pop()
ifnode!=none:
st.append(node)#中
st.append(none)
depth+=1
foriinrange(len(node.children)):#处理孩子
ifnode.children[i]:
st.append(node.children[i])

else:
node=st.pop()
depth-=1
result=max(result,depth)
returnresult

审核编辑 :李倩


声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • C++
    C++
    +关注

    关注

    21

    文章

    2066

    浏览量

    72892
  • 代码
    +关注

    关注

    30

    文章

    4554

    浏览量

    66726
  • 二叉树
    +关注

    关注

    0

    文章

    74

    浏览量

    12238

原文标题:看看这些树的最大深度!

文章出处:【微信号:TheAlgorithm,微信公众号:算法与数据结构】欢迎添加关注!文章转载请注明出处。

收藏 人收藏

    评论

    相关推荐

    树与二叉树的定义

    树型结构 是一类重要的 非线性数据结构 ,其中以树和二叉树最为常用,直观来看,树是以分支关系定义的层次结构。树型结构在客观世界中广泛存在,比如人类社会中的祖辈关系,社会机构组织等等都可以用树来形象
    的头像 发表于 11-24 15:57 532次阅读
    树与<b class='flag-5'>二叉树</b>的定义

    拓扑排序(3)#数据结构

    数据函数二叉树
    未来加油dz
    发布于 :2023年09月05日 10:03:11

    快速排序(2)#数据结构

    数据函数二叉树
    未来加油dz
    发布于 :2023年09月05日 09:58:17

    快速排序(1)#数据结构

    数据函数二叉树
    未来加油dz
    发布于 :2023年09月05日 09:56:46

    循环链表和双向链表(2)#数据结构

    数据函数二叉树
    未来加油dz
    发布于 :2023年09月05日 09:52:24

    平衡二叉树(3)#数据结构

    数据函数二叉树
    未来加油dz
    发布于 :2023年09月05日 09:45:06

    平衡二叉树(2)#数据结构

    数据函数二叉树
    未来加油dz
    发布于 :2023年09月05日 09:43:54

    平衡二叉树(1)#数据结构

    数据函数二叉树
    未来加油dz
    发布于 :2023年09月05日 09:42:30

    希尔排序(2)#数据结构

    数据函数二叉树
    未来加油dz
    发布于 :2023年09月05日 09:41:08

    单源最短路径-迪杰斯特拉算法(3)#数据结构

    数据函数二叉树
    未来加油dz
    发布于 :2023年09月05日 09:25:38

    二叉树二叉树的性质(3)#数据结构

    数据函数二叉树
    未来加油dz
    发布于 :2023年09月05日 09:09:51

    二叉树二叉树的性质(2)#数据结构

    数据函数二叉树
    未来加油dz
    发布于 :2023年09月05日 09:08:32

    二叉树二叉树的性质(1)#数据结构

    数据函数二叉树
    未来加油dz
    发布于 :2023年09月05日 09:06:44

    二叉排序树(2)(2)#数据结构

    数据函数二叉树
    未来加油dz
    发布于 :2023年09月05日 09:04:56

    这么简单的二叉树算法都不会?

    这个题目是leetcode的第572题,要求是这样的:给定两颗二叉树A和B,判断B是否是A的子树。
    的头像 发表于 08-29 11:19 506次阅读
    这么简单的<b class='flag-5'>二叉树</b>算法都不会?