简介 :
二叉树有左右两个子节点 ;
我们可以用一个包含左孩子和右孩子的结构体数组来存储二叉树 :
const int N = 1e6 + 10 ;
// 存储 :
struct Node{
int l , r ;
}a[N];
读入 :
for(int i=1;i<=n;i++) cin >> a[i].l >> a[i].r ;
用链表实现参考 :
二叉树基础知识总结-CSDN博客
例题 :
1 . 二叉树深度
【深基16.例3】二叉树深度 - 洛谷
可以先遍历左子树,然后遍历右子树 , 如果存在,则高度加一;
对于判断叶子节点 : 只需要判断是否值为0即可 ;
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10 ;
// 存储 :
struct Node{
int l , r ;
}a[N];
int n , ans ;
void dfs(int i , int d){
if(i==0) return ; // 叶子结点
// 处理结点
ans = max(ans , d) ;
dfs(a[i].l , d + 1) ; // 左子树
dfs(a[i].r , d + 1) ; // 右子树
}
int main(){
int n ; cin >> n ;
// 读入
for(int i=1;i<=n;i++) cin >> a[i].l >> a[i].r ;
dfs(1,1) ; // 从根节点出发 , 初始深度为1
cout << ans << endl ;
}
2 . P4715 淘汰赛
【深基16.例1】淘汰赛 - 洛谷
虽然实现上和二叉树没有什么关系(用队列实现)
#include<bits/stdc++.h>
using namespace std ;
typedef pair<int,int> PII ;
int main(){
queue<PII> q ;
int n ; cin >> n ;
n = 1<<n ;
for(int i=1;i<=n;i++) {
int x ; cin >> x ;
q.push({x,i}) ;
}
while(q.size() > 2){
auto x = q.front() ; q.pop() ;
auto y = q.front() ; q.pop() ;
if(x.first > y.first){
q.push(x) ;
} else{
q.push(y) ;
}
}
auto x = q.front() ; q.pop() ;
auto y = q.front() ; q.pop() ;
if(x.first > y.first){
cout << y.second << endl ;
}else {
cout << x.second << endl ;
}
}