存储:
struct tree {
int left, right; // 左右子树编号
} a[1000010];计算树的深度:
int dfs_depth(int x) { // x 是子树编号,返回这个节点的深度
if(!x) return 0; // 子树为空,返回 0
return max(dfs_depth(a[x].left), dfs_depth(a[x].right)) + 1; // 子树非空,递归
}例题:P4913 二叉树深度
#include <iostream>
using namespace std;
struct tree { // 存储树的结构体
int left, right;
} a[1000010];
int n;
void input() { // 输入函数,运用模块化程序设计
for(int i = 1; i <= n; i++)
cin >> a[i].left >> a[i].right;
}
int dfs_depth(int x) { // 计算深度
if(!x) return 0;
return max(dfs_depth(a[x].left), dfs_depth(a[x].right)) + 1;
}
int main() { // 简洁的 main 函数
cin >> n;
input(); // 输入
cout << dfs_depth(1); // 整棵树的深度相当于根节点(编号为 1)的深度
return 0;
}二叉树的遍历分为层次遍历和深度优先遍历,这里主要讲深度优先遍历。
分为三种:
- 前序遍历:首先访问根节点,再遍历左子树和右子树。“根左右”
- 中序遍历:首先遍历左子树,再访问根节点,最后遍历右子树。“左根右”
- 后序遍历:首先遍历左子树和右子树,最后访问根节点。“左右根”