【算法】重建二叉树并进行后序遍历的Java实现

人不走空

🌈个人主页:人不走空****

💖系列专栏:算法专题****

**⏰诗词歌赋:**斯是陋室,惟吾德馨

目录

🌈个人主页:人不走空

💖系列专栏:算法专题

⏰诗词歌赋:斯是陋室,惟吾德馨

问题描述

实现思路

实现步骤

[1. 重建二叉树](#1. 重建二叉树)

[2. 后序遍历](#2. 后序遍历)

代码实现

代码解释

总结

作者其他作品:


在二叉树的问题中,给定二叉树的前序遍历(Preorder)和中序遍历(Inorder)序列,如何求得其后序遍历(Postorder)序列是一个经典的面试题。本文将详细介绍如何通过Java实现这一过程。

问题描述

前序遍历(Preorder):按根节点 -> 左子树 -> 右子树的顺序访问节点。

中序遍历(Inorder):按左子树 -> 根节点 -> 右子树的顺序访问节点。

后序遍历(Postorder):按左子树 -> 右子树 -> 根节点的顺序访问节点。

给定前序遍历和中序遍历序列,我们需要构建二叉树并输出其后序遍历序列。

实现思路

  1. 重建二叉树:利用前序遍历和中序遍历的特性,通过递归方法重建二叉树。
  2. 后序遍历二叉树:通过递归方法进行后序遍历并输出结果。

实现步骤

1. 重建二叉树

首先,我们通过前序遍历的第一个元素确定根节点。在中序遍历中找到该根节点的位置,可以将中序遍历数组分为左子树和右子树两部分。递归地对这两部分继续构建左右子树。

2. 后序遍历

在构建好的二叉树上进行后序遍历,按左子树 -> 右子树 -> 根节点的顺序输出节点值。

代码实现

以下是完整的Java实现代码:

java 复制代码
import java.util.HashMap;
import java.util.Map;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class BinaryTree {
    private int preIndex = 0;
    private Map<Integer, Integer> inorderIndexMap = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        for (int i = 0; i < inorder.length; i++) {
            inorderIndexMap.put(inorder[i], i);
        }
        return buildTreeHelper(preorder, 0, inorder.length - 1);
    }

    private TreeNode buildTreeHelper(int[] preorder, int inorderStart, int inorderEnd) {
        if (inorderStart > inorderEnd) {
            return null;
        }
        
        int rootVal = preorder[preIndex++];
        TreeNode root = new TreeNode(rootVal);
        int inorderIndex = inorderIndexMap.get(rootVal);
        
        root.left = buildTreeHelper(preorder, inorderStart, inorderIndex - 1);
        root.right = buildTreeHelper(preorder, inorderIndex + 1, inorderEnd);
        
        return root;
    }

    public void postorderTraversal(TreeNode root) {
        if (root == null) {
            return;
        }
        postorderTraversal(root.left);
        postorderTraversal(root.right);
        System.out.print(root.val + " ");
    }

    public static void main(String[] args) {
        int[] preorder = {3, 9, 20, 15, 7};
        int[] inorder = {9, 3, 15, 20, 7};
        
        BinaryTree binaryTree = new BinaryTree();
        TreeNode root = binaryTree.buildTree(preorder, inorder);
        
        System.out.println("Postorder traversal:");
        binaryTree.postorderTraversal(root);
    }
}

代码解释

  1. TreeNode类:定义二叉树节点的数据结构。

    java 复制代码
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
  2. BinaryTree类:包含重建二叉树和后序遍历的方法。

    • buildTree 方法:接受前序遍历和中序遍历数组,构建并返回二叉树的根节点。
    • buildTreeHelper 方法:递归地构建二叉树。
    • postorderTraversal 方法:递归地进行后序遍历,并输出节点值。
  3. buildTreeHelper方法:通过前序遍历的当前节点值和中序遍历的索引,递归地构建左右子树。

    java 复制代码
    private TreeNode buildTreeHelper(int[] preorder, int inorderStart, int inorderEnd) {
        if (inorderStart > inorderEnd) {
            return null; // Base case: no elements to construct the tree
        }
    
        int rootVal = preorder[preIndex++]; // Get the current root value from preorder traversal
        TreeNode root = new TreeNode(rootVal); // Create the root node
        int inorderIndex = inorderIndexMap.get(rootVal); // Find the index of the root in inorder traversal
    
        // Recursively build the left subtree
        root.left = buildTreeHelper(preorder, inorderStart, inorderIndex - 1);
        // Recursively build the right subtree
        root.right = buildTreeHelper(preorder, inorderIndex + 1, inorderEnd);
    
        return root;
    }
  4. 后序遍历:通过递归方法进行后序遍历,按照左子树 -> 右子树 -> 根节点的顺序输出节点值。

    java 复制代码
    public void postorderTraversal(TreeNode root) {
        if (root == null) {
            return;
        }
        postorderTraversal(root.left);
        postorderTraversal(root.right);
        System.out.print(root.val + " ");
    }
  5. main方法 :创建前序遍历和中序遍历数组,调用buildTree方法构建二叉树,然后调用postorderTraversal方法输出后序遍历结果。

    java 复制代码
    public static void main(String[] args) {
        int[] preorder = {3, 9, 20, 15, 7};
        int[] inorder = {9, 3, 15, 20, 7};
        
        BinaryTree binaryTree = new BinaryTree();
        TreeNode root = binaryTree.buildTree(preorder, inorder);
        
        System.out.println("Postorder traversal:");
        binaryTree.postorderTraversal(root);
    }

总结

通过上述步骤,我们可以实现根据前序遍历和中序遍历序列重建二叉树,并输出其后序遍历序列。这不仅帮助我们加深对二叉树遍历的理解,也为处理相关面试题提供了一个有力的工具。希望这篇文章对你有所帮助!


作者其他作品:

【Java】Spring循环依赖:原因与解决方法

OpenAI Sora来了,视频生成领域的GPT-4时代来了

Java·算法·简单 LeetCode 14. 最长公共前缀 详细解读

【Java】深入理解Java中的static关键字

Java·算法·简单 LeetCode 28. 找出字a符串中第一个匹配项的下标 详细解读

了解 Java 中的 AtomicInteger 类

算法题 --- 整数转二进制,查找其中1的数量

深入理解MySQL事务特性:保证数据完整性与一致性

Java企业应用软件系统架构演变史

相关推荐
葡萄成熟时 !5 小时前
JAVA 常用API学习笔记
java·笔记·学习
鹿角片ljp6 小时前
LeetCode 46. 全排列|吃透回溯
算法·leetcode·职场和发展
鼎艺创新科技6 小时前
不依赖 UE/Unity:我们如何从零搭建一套国产三维 GIS 渲染引擎
人工智能·算法·unity·游戏引擎·三维电子沙盘
剩下了什么6 小时前
float32 与 float64 精度陷阱:如何在 Go 中避免错误使用
开发语言·后端·golang
Rain的Java大神之路6 小时前
介绍一下分布式事务
java·分布式·后端·spring·spring cloud·架构·springcloud
指尖时光.6 小时前
Three.js 超全入门综合案例
开发语言·javascript·ecmascript
暴力求解7 小时前
Linux网络---传输层协议TCP(二)
linux·服务器·开发语言·网络·tcp/ip
吴声子夜歌7 小时前
Java面试题——基础(一)
java·开发语言
小庞在加油7 小时前
WinDbg实战:QT/跨平台项目死锁与无响应问题排查指南
开发语言·qt·windbg·工具
南城以南溫暖如初1477 小时前
外卖CPS实战指南:从技术选型到运营落地全流程解析
java·spring boot·mysql·架构·vue