二叉树的遍历(篇5)由中序和先序序列重建二叉树

2024-09-04 02:08

本文主要是介绍二叉树的遍历(篇5)由中序和先序序列重建二叉树,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

让我们考虑下面的遍历:

中序序列:DBEAFC
前序序列:ABDECF

在Preorder序列中,最左侧的元素是树的根。所以我们知道’A’是给定序列的根。通过在Inorder序列中搜索’A’,我们可以发现’A’左侧的所有元素都在左子树中,右侧的元素在右子树中。所以我们现在知道下面的结构。

                 A/   \/       \D B E     F C

我们递归地按照上面的步骤,得到以下树。

         A/   \
     /       \
    B         C/ \        //     \    /
D       E  F

算法:buildTree()

1)从Preorder中选择一个元素。preIndex++(下面的代码中的preIndex)在下一个递归调用中选择下一个元素。
2)用从Preorder中选的元素创建一个新的树节点tNode。
3)在Inorder中查找所选元素的索引。让索引为inIndex。
4)在inIndex之前调用元素的buildTree,并将构建的树作为tNode的左子树。
5)在inIndex之后调用元素的buildTree,并将构建的树作为tNode的右子树。
6return tNode。

代码


// Java program to construct a tree using inorder and preorder traversal/* A binary tree node has data, pointer to left childand a pointer to right child */
class Node 
{char data;Node left, right;Node(char item) {data = item;left = right = null;}
}class BinaryTree 
{Node root;static int preIndex = 0;/* Recursive function to construct binary of size len fromInorder traversal in[] and Preorder traversal pre[].Initial values of inStrt and inEnd should be 0 and len -1.  The function doesn't do any error checking for cases where inorder and preorder do not form a tree */Node buildTree(char in[], char pre[], int inStrt, int inEnd) {if (inStrt > inEnd) return null;/* Pick current node from Preorder traversal using preIndexand increment preIndex */Node tNode = new Node(pre[preIndex++]);/* If this node has no children then return */if (inStrt == inEnd)return tNode;/* Else find the index of this node in Inorder traversal */int inIndex = search(in, inStrt, inEnd, tNode.data);/* Using index in Inorder traversal, construct left andright subtress */tNode.left = buildTree(in, pre, inStrt, inIndex - 1);tNode.right = buildTree(in, pre, inIndex + 1, inEnd);return tNode;}/* UTILITY FUNCTIONS *//* Function to find index of value in arr[start...end]The function assumes that value is present in in[] */int search(char arr[], int strt, int end, char value) {int i;for (i = strt; i <= end; i++) {if (arr[i] == value)return i;}return i;}/* This funtcion is here just to test buildTree() */void printInorder(Node node) {if (node == null)return;/* first recur on left child */printInorder(node.left);/* then print the data of node */System.out.print(node.data + " ");/* now recur on right child */printInorder(node.right);}// driver program to test above functionspublic static void main(String args[]) {BinaryTree tree = new BinaryTree();char in[] = new char[]{'D', 'B', 'E', 'A', 'F', 'C'};char pre[] = new char[]{'A', 'B', 'D', 'E', 'C', 'F'};int len = in.length;Node root = tree.buildTree(in, pre, 0, len - 1);// building the tree by printing inorder traversalSystem.out.println("Inorder traversal of constructed tree is : ");tree.printInorder(root);}
}

这篇关于二叉树的遍历(篇5)由中序和先序序列重建二叉树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1134692

相关文章

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动

关于最长递增子序列问题概述

《关于最长递增子序列问题概述》本文详细介绍了最长递增子序列问题的定义及两种优化解法:贪心+二分查找和动态规划+状态压缩,贪心+二分查找时间复杂度为O(nlogn),通过维护一个有序的“尾巴”数组来高效... 一、最长递增子序列问题概述1. 问题定义给定一个整数序列,例如 nums = [10, 9, 2

C++中使用vector存储并遍历数据的基本步骤

《C++中使用vector存储并遍历数据的基本步骤》C++标准模板库(STL)提供了多种容器类型,包括顺序容器、关联容器、无序关联容器和容器适配器,每种容器都有其特定的用途和特性,:本文主要介绍C... 目录(1)容器及简要描述‌php顺序容器‌‌关联容器‌‌无序关联容器‌(基于哈希表):‌容器适配器‌:(

uva 10131 最长子序列

题意: 给大象的体重和智商,求体重按从大到小,智商从高到低的最长子序列,并输出路径。 代码: #include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <cstring>#include <cmath>#include <stack>#include <vect

POJ1631最长单调递增子序列

最长单调递增子序列 import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.PrintWriter;import java.math.BigInteger;import java.util.StringTokenizer;publ

leetcode105 从前序与中序遍历序列构造二叉树

根据一棵树的前序遍历与中序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。 例如,给出 前序遍历 preorder = [3,9,20,15,7]中序遍历 inorder = [9,3,15,20,7] 返回如下的二叉树: 3/ \9 20/ \15 7   class Solution {public TreeNode buildTree(int[] pr

PHP实现二叉树遍历(非递归方式,栈模拟实现)

二叉树定义是这样的:一棵非空的二叉树由根结点及左、右子树这三个基本部分组成,根据节点的访问位置不同有三种遍历方式: ① NLR:前序遍历(PreorderTraversal亦称(先序遍历)) ——访问结点的操作发生在遍历其左右子树之前。 ② LNR:中序遍历(InorderTraversal) ——访问结点的操作发生在遍历其左右子树之中(间)。 ③ LRN:后序遍历(PostorderT

day-50 求出最长好子序列 I

思路 二维dp,dp[i][h]表示nums[i] 结尾,且有不超过 h 个下标满足条件的最长好子序列的长度(0<=h<=k),二维数组dp初始值全为1 解题过程 状态转换方程: 1.nums[i]==nums[j],dp[i,h]=Math.max(dp[i,h],dp[j,h]+1) 2.nums[i]!=nums[j],dp[i,h]=Math.max(dp[i,h],dp[j,h-1

LeetCode:3177. 求出最长好子序列 II 哈希表+动态规划实现n*k时间复杂度

3177. 求出最长好子序列 II 题目链接 题目描述 给你一个整数数组 nums 和一个非负整数k 。如果一个整数序列 seq 满足在下标范围 [0, seq.length - 2] 中 最多只有 k 个下标i满足 seq[i] != seq[i + 1] ,那么我们称这个整数序列为好序列。请你返回 nums中好子序列的最长长度。 实例1: 输入:nums = [1,2,1,1,3],

react笔记 8-17 属性绑定 class绑定 引入图片 循环遍历

1、绑定属性 constructor(){super()this.state={name:"张三",title:'我是一个title'}}render() {return (<div><div>aaaaaaa{this.state.name}<div title={this.state.title}>我是一个title</div></div></div>)} 绑定属性直接使用花括号{}   注