【笔记】二叉树学习笔记

· · 算法·理论

存储:

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;
}

二叉树的遍历分为层次遍历和深度优先遍历,这里主要讲深度优先遍历。

分为三种: