跳到正文

个人记录

P4913 二叉树深度 题解

houyingran01约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年3月6日
更新
2026年3月6日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

P4913 【深基16.例3】二叉树深度

题目传送门

知识提要:

P1:认识二叉树

在做这道题前我们要知道什么叫做二叉树

代码
A:  1         B:    1         C:    1
   / \             / \             / \
  2   3           2   3           2   3
 / \                             / \ / \
4   5                           4  5 6  7

这三种树都叫二叉树!

虽然这三种树都叫做二叉树,但A\texttt{A}和B,C\texttt{B,C}却有着不一样的名字 A\texttt{A}:完整二叉树——每一个父亲节点的子节点数量既可以是0也可以是2 B,C\texttt{B,C}:满二叉树——所有子节点的深度都是2


P2:二叉树深度

还是以ABC\texttt{ABC}三幅图片为例: A\texttt{A}的深度:33  |  B\texttt{B}的深度:22  |  C\texttt{C}的深度:33

树的深度(高度):从根节点到最远子节点的最长路径上的节点数【看有几层就行,记得算根节点】!


前置知识OK了,接下来上代码~

AC代码:

C++
#include<bits/stdc++.h>
using namespace std;
int n,i,l[1000010],r[1000010],ans=-1;
struct node{
	int name;
	node *lchild;//左子树
	node *rchild;//右子树
};
node *buildtree(int deep,int x){//建树
	if(x==0){//空节点更新最大深度
		ans=max(ans,deep-1);
		return NULL;
	}
	node *root=new node;
	root->name=x;
	root->lchild=buildtree(deep+1,l[x]);//构建左子树
  root->rchild=buildtree(deep+1,r[x]);//构建右子树
	return root;
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>l[i]>>r[i];// 输入各个节点的左子右子节点
    }
    node *root=buildtree(1,1);//从根节点开始建树(编号为1,深度为1)
    cout<<ans;
    return 0;
}

完事了!!!

原文