[模版总结] - 树的基本算法1 - 遍历

树结构定义

一种非线性存储结构,具有存储"一对多"关系的数据元素集合

种类

  • General Tree
    • Trie
    • B/B+ 树
  • 二叉树
    • 满/完满/完全二叉树
      • 完美BT : 除了叶子结点外所有节点都有两个字节点,每一层都完满填充
      • 完全BT: 除最后一层以外其他每一层都完美填充,最后一层从左到右紧密填充
      • 完满BT: 除了叶子结点外所有节点都有两个字节点
    • 二叉搜索树 BST
      • 平衡BST
        • 红黑树
        • 伸展树
        • 自平衡二叉查找树AVL
        • 替罪羊树
    • 线索二叉树
    • 霍夫曼树/最优二叉树

二叉树遍历方式

所有二叉树基本遍历时间复杂度均为:, N代表结点数量。

前序遍历 (根左右)

递归写法

java 复制代码
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        dc(root, res);
        return res;
        
    }

    private void dc(TreeNode root, List<Integer> res) {
        if (root==null) return;

        res.add(root.val);
        dc(root.left, res);
        dc(root.right, res);
    }
}

中序遍历 (左根右)

递归写法

java 复制代码
class Solution {
    List<Integer> res;
    public List<Integer> inorderTraversal(TreeNode root) {
        res = new ArrayList<>();
        dc(root);

        return res;
    }

    private void dc(TreeNode root) {
        if (root==null) return;

        dc(root.left);
        res.add(root.val);
        dc(root.right);
    }
}

后续遍历 (左右根)

java 复制代码
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        dc(root, res);
        return res;
    }

    private void dc(TreeNode root, List<Integer> res) {

        if (root==null) return;

        dc(root.left, res);
        dc(root.right, res);
        res.add(root.val);
    }    
}

层级遍历 I - 自上而下

树/图类层级遍历直接BFS即可

java 复制代码
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();

        if (root==null) return res;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);

        while (!q.isEmpty()) {
            int size = q.size();

            List<Integer> tmp = new ArrayList<>();
            for (int i=0; i<size; i++) {
                TreeNode curr = q.poll();
                tmp.add(curr.val);
                if (curr.left!=null) q.add(curr.left);
                if (curr.right!=null) q.add(curr.right);
            }
            res.add(tmp);
        }

        return res;
    }
}

层级遍历 II - 自下而上

java 复制代码
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        
        if (root==null) return res;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);

        while (!q.isEmpty()) {
            int size = q.size();
            List<Integer> tmp = new ArrayList<>();
            for (int i=0; i<size; i++) {
                TreeNode curr = q.poll();
                if (curr.left!=null) q.add(curr.left);
                if (curr.right!=null) q.add(curr.right);
                tmp.add(curr.val);
            }

            res.add(0, tmp);
        }

        return res;
    }
}

ZigZag 遍历

java 复制代码
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(root, 0, res);
        return res;
    }

    private void dfs(TreeNode root, int height, List<List<Integer>> res) {
        if (root==null) return;
        if (res.size()<=height) res.add(new ArrayList<>());

        if (height%2==0) {
            res.get(height).add(root.val);
        } else {
            res.get(height).add(0, root.val);
        }

        dfs(root.left, height+1, res);
        dfs(root.right, height+1, res);
    }
}

一些特别的遍历:

逐列遍历

, N表示dfs遍历时间复杂度,C表示列数,R表示每一列的行数

java 复制代码
class Solution {
    TreeMap<Integer, List<Pair<Integer, Integer>>> colMap;
    public List<List<Integer>> verticalOrder(TreeNode root) {
        if (root==null) return new ArrayList<>();

        colMap = new TreeMap<>();
        dfs(root, 0, 0);

        List<List<Integer>> res = new ArrayList<>();

        for (int idx: colMap.keySet()) {
            Collections.sort(colMap.get(idx), (a, b) -> {
                return a.getKey()-b.getKey();
            });

            List<Integer> tmp = new ArrayList<>();
            for (Pair<Integer, Integer> a: colMap.get(idx)) {
                tmp.add(a.getValue());
            }

            res.add(tmp);
        }

        return res;

    }

    private void dfs(TreeNode root, int row, int col) {
        if (root==null) return;

        colMap.putIfAbsent(col, new ArrayList<>());
        colMap.get(col).add(new Pair<>(row, root.val));

        dfs(root.left, row+1, col-1);
        dfs(root.right, row+1, col+1);
    }
}
相关推荐
在努力的前端小白3 小时前
Spring Boot 敏感词过滤组件实现:基于DFA算法的高效敏感词检测与替换
java·数据库·spring boot·文本处理·敏感词过滤·dfa算法·组件开发
Coovally AI模型快速验证5 小时前
农田扫描提速37%!基于检测置信度的无人机“智能抽查”路径规划,Coovally一键加速模型落地
深度学习·算法·yolo·计算机视觉·transformer·无人机
pusue_the_sun5 小时前
数据结构:二叉树oj练习
c语言·数据结构·算法·二叉树
一叶飘零_sweeeet5 小时前
从繁琐到优雅:Java Lambda 表达式全解析与实战指南
java·lambda·java8
RaymondZhao345 小时前
【全面推导】策略梯度算法:公式、偏差方差与进化
人工智能·深度学习·算法·机器学习·chatgpt
艾伦~耶格尔6 小时前
【集合框架LinkedList底层添加元素机制】
java·开发语言·学习·面试
zhangfeng11336 小时前
DBSCAN算法详解和参数优化,基于密度的空间聚类算法,特别擅长处理不规则形状的聚类和噪声数据
算法·机器学习·聚类
一只叫煤球的猫6 小时前
🕰 一个案例带你彻底搞懂延迟双删
java·后端·面试
最初的↘那颗心6 小时前
Flink Stream API 源码走读 - print()
java·大数据·hadoop·flink·实时计算
啊阿狸不会拉杆6 小时前
《算法导论》第 32 章 - 字符串匹配
开发语言·c++·算法