数据结构和算法之【二叉树】

目录

认识二叉树

二叉树的遍历

广度优先遍历

深度优先遍历

前序遍历

中序遍历

后序遍历

LeetCode-102题(二叉树的层序遍历)

题解

测试结果

LeetCode-144题(二叉树的前序遍历)

题解

方法一:借助栈来解题

方法二:使用递归解题

测试结果

LeetCode-94题(二叉树的中序遍历)

题解

方法一:借助栈来解题

方法二:使用递归解题

测试结果

LeetCode-145题(二叉树的后序遍历)

题解

方法一:借助栈来解题

方法二:使用递归解题

测试结果


认识二叉树

二叉树中每个节点最多有2个子节点,最顶层的节点称为根节点,没有字节点的称为叶子节点

如上图中的二叉树:

  • 节点1节点3有2个子节点,节点2有1个子节点,其余节点没有子节点
  • 节点1为二叉树中最顶层的节点,它就是根节点
  • 节点4节点5节点6没有子节点,它们是叶子节点

二叉树的遍历

分为两种遍历方式:广度优先遍历和深度优先遍历

广度优先遍历

也叫程序遍历,优先访问距离根节点最近的节点

深度优先遍历

对于二叉树,深度优先遍历又分为如下3种遍历方法

前序遍历

对于每一棵子树,先访问当前节点,然后是左子树,最后是右子树

中序遍历

对于每一棵子树,先访问左子树,然后是当前节点,最后是右子树

后序遍历

对于每一棵子树,先访问左子树,然后是右子树,最后是当前节点

LeetCode-102题(二叉树的层序遍历)

题解

java 复制代码
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        // 借助队列来解题
        LinkedList<TreeNode> queue = new LinkedList<>();
        // 将根节点入队
        queue.offer(root);
        // 记录当前层的节点数(当前第一层,只有一个节点,根节点)
        int c1 = 1;
        // 只要队列不为空
        while (!queue.isEmpty()) {
            // 定义集合存储每一层的节点的值
            List<Integer> nodeValInnerList = new ArrayList<>();
            // 用于记录下一层的节点数量
            int c2 = 0;
            // 处理每一层节点
            for (int i = 0; i < c1; i++) {
                TreeNode currTreeNode = queue.poll();
                nodeValInnerList.add(currTreeNode.val);
                if (currTreeNode.left != null) {
                    queue.offer(currTreeNode.left);
                    c2++;
                }
                if (currTreeNode.right != null) {
                    queue.offer(currTreeNode.right);
                    c2++;
                }
            }
            result.add(nodeValInnerList);
            c1 = c2;
        }
        return result;
    }
}

测试结果

LeetCode-144题(二叉树的前序遍历)

题解

方法一:借助栈来解题

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

    private void order(TreeNode root, List<Integer> pre) {
        //当前节点
        TreeNode curr = root;
        //借助栈
        LinkedList<TreeNode> stack = new LinkedList<>();
        //最近一次pop的元素
        TreeNode pop = null;
        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                stack.push(curr);
                pre.add(curr.val);
                //待处理左节点
                curr = curr.left;
            } else {
                //栈不为空
                TreeNode peek = stack.peek();
                //右节点为空
                if (peek.right == null) {
                    pop = stack.pop();
                }
                //右节点处理完
                else if (peek.right == pop) {
                    pop = stack.pop();
                }
                //处理右节点
                else {
                    curr = peek.right;
                }
            }
        }
    }
}

方法二:使用递归解题

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

    /**
     * 二叉树的前序遍历(使用递归方式)
     */
    private void preOrder(TreeNode node, List<Integer> result) {
        // 递归的结束条件
        if (node == null) {
            return;
        }
        // 当前节点
        result.add(node.val);
        // 处理左子树
        preOrder(node.left, result);
        // 处理右子树
        preOrder(node.right, result);
    }
}

测试结果

LeetCode-94题(二叉树的中序遍历)

题解

方法一:借助栈来解题

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

    private void order(TreeNode root, List<Integer> mid) {
        //当前节点
        TreeNode curr = root;
        //借助栈
        LinkedList<TreeNode> stack = new LinkedList<>();
        //最近一次pop的元素
        TreeNode pop = null;
        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                stack.push(curr);
                //待处理左节点
                curr = curr.left;
            } else {
                //栈不为空
                TreeNode peek = stack.peek();
                //右节点为空
                if (peek.right == null) {
                    mid.add(peek.val);
                    pop = stack.pop();
                }
                //右节点处理完
                else if (peek.right == pop) {
                    pop = stack.pop();
                }
                //处理右节点
                else {
                    mid.add(peek.val);
                    curr = peek.right;
                }
            }
        }
    }
}

方法二:使用递归解题

java 复制代码
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        inOrder(root, result);
        return result;
    }

    /**
     * 二叉树的中序遍历(使用递归方式)
     */
    private void inOrder(TreeNode node, List<Integer> result) {
        // 递归的结束条件
        if (node == null) {
            return;
        }
        // 处理左子树
        inOrder(node.left, result);
        // 当前节点
        result.add(node.val);
        // 处理右子树
        inOrder(node.right, result);
    }
}

测试结果

LeetCode-145题(二叉树的后序遍历)

题解

方法一:借助栈来解题

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

    private void order(TreeNode root, List<Integer> post) {
        //当前节点
        TreeNode curr = root;
        //借助栈
        LinkedList<TreeNode> stack = new LinkedList<>();
        //最近一次pop的元素
        TreeNode pop = null;
        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                stack.push(curr);
                //待处理左节点
                curr = curr.left;
            } else {
                //栈不为空
                TreeNode peek = stack.peek();
                //右节点为空
                if (peek.right == null) {
                    pop = stack.pop();
                    post.add(peek.val);
                }
                //右节点处理完
                else if (peek.right == pop) {
                    pop = stack.pop();
                    post.add(peek.val);
                }
                //处理右节点
                else {
                    curr = peek.right;
                }
            }
        }
    }
}

方法二:使用递归解题

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

    /**
     * 二叉树的后序遍历(使用递归方式)
     */
    private void postOrder(TreeNode node, List<Integer> result) {
        // 递归的结束条件
        if (node == null) {
            return;
        }
        // 处理左子树
        postOrder(node.left, result);
        // 处理右子树
        postOrder(node.right, result);
        // 当前节点
        result.add(node.val);
    }
}

测试结果

相关推荐
ambition202423 小时前
操作系统同步:读者-写者问题与读写公平法详解(附每个 PV 操作含义)
linux·开发语言·数据结构·unix
chuan.bai5 小时前
Java RAG 实战(第 11 篇):RAG 知识工作台网页
java·开发语言·人工智能
0x538 小时前
网站通信(一)
java
Terra.K8 小时前
Java异常学习[特殊字符]
java·开发语言·学习
mCell8 小时前
Lua 编程入门:从基础语法到元表
javascript·算法·lua
葡萄城技术团队10 小时前
InfluxDB 2\.x 深度解析:核心架构、Flux 函数与制造业落地指南(三)
java·开发语言·架构
Super 含10 小时前
Android 启动优化(五):线程、GC 与 IO 为什么会拖慢启动?
java·服务器·数据库
counting money10 小时前
Java IO流详解:从InputStream到文件操作实战
java·开发语言·python
wuyk55510 小时前
98.C语言易混难点:字符数组与字符串指针的底层差异
c语言·开发语言·c++·stm32·嵌入式硬件·算法