


When we have a
Pre-order traversal sequence: 1,3,7,9,5,11
In-order traversal sequence: 9,7,3,1,5, 11
We can easily write the corresponding binary tree with a pen. But how to implement it using code?
Let’s briefly talk about the basic ideas.
First of all, the order of pre-order traversal is based on the order of root-left child-right child, then the first thing we can confirm is the pre-order traversal sequence The first number is the root node, and then the in-order traversal is traversed in the order of left child-root-right child. We have confirmed the root node through pre-order traversal, then we only need to find the location of the root node in in-order traversal, and then we can easily distinguish those nodes that belong to the left subtree and those that belong to the right subtree. . As shown in the figure below:
We determine the number 1 as the root node, and then determine it according to the traversal order of the in-order traversal. In the in-order traversal sequence, all the left subtree nodes of the number 1 are left subtree nodes, and all the right subtrees are right subtrees. Through the number of left subtree nodes, it can be concluded that the three consecutive numbers from the root node in the preorder traversal sequence belong to the left subtree, and the remaining ones are the right subtree. In this way, the above steps are repeated in the sequence of the left and right subtrees, until finally no child nodes are found.
The implementation code is as follows:
1 package com.tree.traverse; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 /** 7 * @author Caijh 8 * 9 * 2017年6月2日 下午7:21:10 10 */ 11 12 public class BuildTreePreOrderInOrder { 13 14 /** 15 * 1 16 * / \ 17 * 3 5 18 * / \ 19 * 7 11 20 * / 21 * 9 22 */ 23 public static int treeNode = 0;//记录先序遍历节点的个数 24 private List<node> nodeList = new ArrayList();//层次遍历节点的队列 25 public static void main(String[] args) { 26 BuildTreePreOrderInOrder build = new BuildTreePreOrderInOrder(); 27 int[] preOrder = { 1, 3, 7, 9, 5, 11}; 28 int[] inOrder = { 9, 7, 3, 1, 5, 11}; 29 30 treeNode = preOrder.length;//初始化二叉树的节点数 31 Node root = build.buildTreePreOrderInOrder(preOrder, 0, preOrder.length - 1, inOrder, 0, preOrder.length - 1); 32 System.out.print("先序遍历:"); 33 build.preOrder(root); 34 System.out.print("\n中序遍历:"); 35 build.inOrder(root); 36 System.out.print("\n原二叉树:\n"); 37 build.prototypeTree(root); 38 } 39 40 /** 41 * 分治法 42 * 通过先序遍历结果和中序遍历结果还原二叉树 43 * @param preOrder 先序遍历结果序列 44 * @param preOrderBegin 先序遍历起始位置下标 45 * @param preOrderEnd 先序遍历末尾位置下标 46 * @param inOrder 中序遍历结果序列 47 * @param inOrderBegin 中序遍历起始位置下标 48 * @param inOrderEnd 中序遍历末尾位置下标 49 * @return 50 */ 51 public Node buildTreePreOrderInOrder(int[] preOrder, int preOrderBegin, int preOrderEnd, int[] inOrder, int inOrderBegin, int inOrderEnd) { 52 if (preOrderBegin > preOrderEnd || inOrderBegin > inOrderEnd) { 53 return null; 54 } 55 int rootData = preOrder[preOrderBegin];//先序遍历的第一个字符为当前序列根节点 56 Node head = new Node(rootData); 57 int divider = findIndexInArray(inOrder, rootData, inOrderBegin, inOrderEnd);//找打中序遍历结果集中根节点的位置 58 int offSet = divider - inOrderBegin - 1;//计算左子树共有几个节点,节点数减一,为数组偏移量 59 Node left = buildTreePreOrderInOrder(preOrder, preOrderBegin + 1, preOrderBegin + 1 + offSet, inOrder, inOrderBegin,inOrderBegin + offSet); 60 Node right = buildTreePreOrderInOrder(preOrder, preOrderBegin + offSet + 2, preOrderEnd, inOrder, divider + 1, inOrderEnd); 61 head.left = left; 62 head.right = right; 63 return head; 64 } 65 /** 66 * 通过先序遍历找到的rootData根节点,在中序遍历结果中区分出:中左子树和右子树 67 * @param inOrder 中序遍历的结果数组 68 * @param rootData 根节点位置 69 * @param begin 中序遍历结果数组起始位置下标 70 * @param end 中序遍历结果数组末尾位置下标 71 * @return return中序遍历结果数组中根节点的位置 72 */ 73 public int findIndexInArray(int[] inOrder, int rootData, int begin, int end) { 74 for (int i = begin; i =treeNode)//当所有有效节点都遍历到了就结束遍历137 break;138 j+=2;//每次存储两个子节点,所以每次加2139 }140 }141 int flag=0,floor=1;142 for(Node node:nodeList){143 if(node!=null)144 System.out.print(node.val+" ");145 else146 System.out.print("# ");//#号表示空节点147 flag++;148 /**149 * 逐层遍历输出二叉树150 * 151 */152 if(flag>=Math.pow(2, floor-1)){153 flag=0;154 floor++;155 System.out.println();156 }157 }158 }159 }160 /**161 * 内部类162 * 1.每个Node类对象为一个节点,163 * 2.每个节点包含根节点,左子节点和右子节点164 */165 class Node {166 Node left;167 Node right;168 int val;169 public Node(int val) {170 this.val = val;171 }172 }173 }</node>
Running result:
Finally, the basic idea of outputting the binary tree layer by layer:
* 1. Because the derived binary tree is stored in the sub-object of the Node class object, (similar to the structure of the c language) if through recursion It is not easy to implement hierarchical traversal
* 2. Here, the List queue is used to save Node object nodes layer by layer to realize the hierarchical traversal output of the binary tree
* 3. If the position of the parent node is i, then the child node The positions are 2i and 2i+1; according to this rule, traverse layer by layer and find the child nodes through the saved parent nodes. And save, keep traversing downwards to save.
The above is the detailed content of Restore the binary tree through the sequence after pre-order traversal and in-order traversal. For more information, please follow other related articles on the PHP Chinese website!

Java是一种流行的编程语言,具有强大的文件处理功能。在Java中,遍历文件夹并获取所有文件名是一种常见的操作,可以帮助我们快速定位和处理特定目录下的文件。本文将介绍如何在Java中实现遍历文件夹并获取所有文件名的方法,并提供具体的代码示例。1.使用递归方法遍历文件夹我们可以使用递归方法来遍历文件夹,递归方法是一种自身调用自身的方式,可以有效地遍历文件夹中

PHPglob()函数使用示例:遍历指定文件夹中的所有文件在PHP开发中,经常需要遍历指定文件夹中的所有文件,以实现文件批量操作或读取。PHP的glob()函数正是用来实现这种需求的。glob()函数可以通过指定一个通配符匹配模式,来获取指定文件夹中符合条件的所有文件的路径信息。在这篇文章中,我们将会演示如何使用glob()函数来遍历指定文件夹中的所有文件

概念差异:Iterator:Iterator是一个接口,代表一个从集合中获取值的迭代器。它提供了MoveNext()、Current()和Reset()等方法,允许你遍历集合中的元素,并对当前元素进行操作。Iterable:Iterable也是一个接口,代表一个可迭代的对象。它提供了Iterator()方法,用于返回一个Iterator对象,以便于遍历集合中的元素。使用方式:Iterator:要使用Iterator,需要先获得一个Iterator对象,然后调用MoveNext()方法来移动到下一

Python3.x中如何使用os模块遍历目录中的文件在Python中,我们可以使用os模块来进行文件和目录的操作。os模块是Python标准库中的一个重要模块,提供了许多和操作系统相关的功能。在本文中,我们将介绍如何使用os模块来遍历一个目录中的所有文件。首先,我们需要导入os模块:importos接下来,我们可以使用os.walk()函数来遍历目录。

我们得到了用于形成链表的整数值。任务是使用递归方法先插入然后遍历单链表。在末尾递归添加节点如果head为NULL→将节点添加到head否则添加到head(head→next)递归遍历节点如果head为NULL→退出否则打印(head→next)示例输入−1-2-7-9-10输出输出strong>−链表:1→2→7→9→10→NULL输入−12-21-17-94-18输出−链表:12→21→17→94→18→NULL下面程序中使用的方法如下在这种方法中,我们将使用函数添加节点并遍历单链表并递

Iterator简介Iterator是Java中用于遍历集合的接口。它提供了一组方法,允许您以一种顺序的方式访问集合中的元素。您可以使用Iterator来遍历List、Set和Map等集合类型。演示代码:Listlist=newArrayList();list.add("one");list.add("two");list.add("three");Iteratoriterator=list.iterator();while(iter

Iterator接口Iterator接口是Java集合框架中定义的一个接口,它提供了一系列用于遍历集合元素的方法。Iterator接口定义了以下主要方法:hasNext():返回一个布尔值,指示是否存在下一个元素。next():返回下一个元素,如果不存在下一个元素,则抛出NoSuchElementException异常。remove():删除当前指向的元素。以下是使用Iterator接口遍历集合的示例代码:Listlist=newArrayList();list

Python的range()函数:生成数字序列,需要具体代码示例Python是一种功能强大的编程语言,其中有许多内置的函数对于编写程序非常有帮助。其中之一就是range()函数,它用于生成一个数字序列。本文将详细介绍range()函数的用法,并通过具体的代码示例来说明。range()函数的基本语法如下:range(start,stop,step)其中,s


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),