The binary tree and binary tree are restored through the first and middle traversal sequences.

Source: Internet
Author: User

The binary tree and binary tree are restored through the first and middle traversal sequences.

When we have

First order traversal sequence: 1, 3, 7, 9, 5, 11

Sequential traversal sequence: 9, 7, 3, 1, 5, 11

We can easily write the corresponding binary tree using a pen. But how can I implement it with code?

Next, let's talk about the basic idea.

First, the first order of traversal is based onRoot-left child-right childSo we can first confirm that the first number of first traversal sequences is the root node, and thenLeft child-root-right child. We confirm the root node through the first sequential traversal, then we only need to find the root node location in the middle sequential traversal, and then we can distinguish the nodes that belong to the left subtree, the nodes that belong to the right subtree. For example:

We determine that number 1 is the root node, and then determine according to the traversal order of the central order traversal sequence. The left side of number 1 in the middle order traversal sequence is all left subtree nodes, and the right side is all right subtree. Through the number of left subtree nodes, it is obtained that the number of three consecutive numbers following the root node in the first sequential traversal sequence belongs to the left subtree, and the rest is the right subtree. In this way, repeat the above steps in the left and right subtree sequence, and finally find no child node.

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 * June 2, 2017 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; // record the number of first-order traversal nodes 24 private List <Node> nodeList = new ArrayList <> (); // The queue 25 public static void ma of the layered traversal Node In (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; // initialize the number of nodes in the binary tree 31 Node root = build. buildTreePreOrderInOrder (preOrder, 0, preOrder. length-1, inOrder, 0, preOrder. length-1); 32 System. out. print ("sequential traversal:"); 33 build. preOrder (root); 34 System. out. Print ("\ n middle-order traversal:"); 35 build. inOrder (root); 36 System. out. print ("\ n original binary tree: \ n"); 37 build. prototypeTree (root ); 38} 39 40/** 41 * Division and Control Law 42 * restore a binary tree 43 * @ param preOrder first traverse the result sequence 44 * @ param preOrderBegin first ordinal traversal start position subscript 45 * @ param preOrderEnd first order traversal end position subscript 46 * @ param inOrder in ordinal traversal result sequence 47 * @ param inOrderBegin ordinal traversal start position subscript 48 * @ param inOrderEnd in the middle order, traverse the end position subscript 49 * @ return 50 */51 public Node buildTree PreOrderInOrder (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]; // the first character for first-order traversal is the current sequence root Node 56 Node head = new Node (rootData ); 57 int divider = findIndexInArray (inOrder, rootData, inOrderBegin, inOrderEnd); // you can specify Position 58 int offSet = divider-inOrderBegin-1; // calculate the number of nodes in the left subtree by one, which is the array offSet 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 hea D; 64} 65/** 66 * The rootData root node found through first-order traversal is distinguished in the middle-order traversal result: center left subtree and right subtree 67 * @ param inOrder result array of sequential traversal 68 * @ param rootData root node location 69 * @ param begin result array start position subscript 70 *@ the position at the end of the param end result array is 71 * @ return the position of the root node in the result array. 72 */73 public int findIndexInArray (int [] inOrder, int rootData, int begin, int end) {74 for (int I = begin; I <= end; I ++) {75 if (inOrder [I] = rootData) 76 return I; 77} 78 re Turn-1; 79} 80/** 81 * Binary Tree first traversal result 82 * @ param n 83 */84 public void preOrder (Node n) {85 if (n! = Null) {86 System. out. print (n. val + ","); 87 preOrder (n. left); 88 preOrder (n. right); 89} 90} 91/** 92 * result 93 * @ param n 94 */95 public void inOrder (Node n) {96 if (n! = Null) {97 inOrder (n. left); 98 System. out. print (n. val + ","); 99 inOrder (n. right); 100} 101} 102/** 103 * restored Binary Tree 104 * binary number level traversal 105 * Basic Idea: 106*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), it is not easy to implement 107*2 If the hierarchy traversal is implemented through recursion. here, the List queue is used to store Node object nodes layer by layer to achieve the output of 108*3 for hierarchical traversal of Binary Trees. if the parent node is I, the child nodes are 2i and 2i + 1. Based on this rule, traverse layer by layer and find the child node by saving the parent node. And save, and continue to traverse and save. 109 * @ param tree110 */111 public void prototypeTree (Node tree) {112 // use list to store the Node 113 if (tree! = Null) {114 if (tree! = Null) 115 nodeList. add (tree); 116 nodeList. add (tree. left); 117 nodeList. add (tree. right); 118 int count = 3; 119 // starting from the third layer 120 for (int I = 3; count <treeNode; I ++) {121 // The subscript 122 int index = (int) Math of the parent node of the first child node in layer I. pow (2, i-1-1)-1; 123/* 124 * The number of nodes on each layer of the Binary Tree traverses 125 * because the maximum number of nodes on the I layer is 2 to the power of the I-1, 126 */127 for (int j = 1; j <= Math. pow (2, I-1);) {128 // calculate the number of valid nodes, compared with the total number of traversal sequences, as a marker for judging the end of the loop 129 if (nodeList. get (index ). left! = Null) 130 count ++; 131 if (nodeList. get (index). right! = Null) 132 count ++; 133 nodeList. add (nodeList. get (index ). left); 134 nodeList. add (nodeList. get (index ). right); 135 index ++; 136 if (count> = treeNode) // when all valid nodes are traversed, The traversal ends with 137 break; 138 j + = 2; // store two subnodes each time, so add 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 ("#"); // # indicates the empty node 147 flag ++; 148/** 149 * layer-by-layer traversal of the output binary tree 150*151 */152 if (flag> = Math. pow (2, floor-1) {153 flag = 0; 154 floor ++; 155 System. out. println (); 156} 157} 158} 159/** 160 * internal class 161*1. each Node class object is a Node, 163*2. each Node contains the root Node, the left subnode and the right subnode 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}

 

Running result:

Finally, the basic idea of outputting a binary tree layer by layer is as follows:
* 1. Because the derived binary tree is stored in the sub-object of the Node object (similar to the structure of the C language), it is not easy to implement hierarchical traversal through recursion.
* 2. The List queue is used to store Node object nodes layer by layer to achieve hierarchical traversal of the binary tree.
* 3. If the parent node is I, the child nodes are 2i and 2i + 1. Traverse layer by layer based on this rule and find the child node by saving the parent node. And save, and continue to traverse and save.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.