[Data structure] binary tree creation and traversal

Source: Internet
Author: User

Lab report: Two fork tree creation and traversal one, problem description

Binary tree is a wide range of practical nonlinear structure, a non-empty binary tree has only one root node, each node has a maximum of two subtrees, we call Zuozi and right subtree, when a node of the left and right subtree is empty, Vaughn called this node as a leaf node.

The binary tree has some very good properties, which are not mentioned here. Considering how to store a tree, this experiment chooses to use the chain storage structure--two-fork linked list; If you know beforehand that the two tree you need to store is a full two tree or a full binary tree, you might consider using sequential storage, or you would waste a lot of storage space.

For a two-fork tree, there are three ways to traverse it-first order, middle sequence and post order. It can be proved that a fixed two-fork tree with the sequence traversal, post-order traversal generated sequences are 1-1 corresponding, based on this point, we can binate sequence or sequential sequence to get the only corresponding two-fork tree. This is the theoretical basis of this experiment to create a two-fork tree.

It is worth noting that a middle sequence traversal sequence and a two-fork tree are not 1-1 correspondence, that is, the shape of a two-forked tree corresponding to a sequence is not fixed, even if the void node is added as in this experiment is not 1-1 . Corresponding, so the middle sequence is not able to generate a binary tree.

This experiment mainly gives the first order to create a two-fork tree, and the middle sequence to traverse the tree.

Second, data structure--Two fork list

The binary chain list is a chain storage structure of two-fork tree, and its structure has a natural fit with the nature of the two-fork tree.

We know that the nodes of the binary tree need to be saved information: the current node information, Zuozi, right subtree. Based on such a structure, we dispose of the data field and the Pointer field in a node: The data field holds the information of the node itself; The pointer field is divided into the left and right pointer fields, pointing to the left and right subtree of the node, and, if necessary, a link field pointing to the parent node of the node (parent knot), which, of course, becomes a triple-linked There is no big difference between the triple-linked list and the two-fork list, but the triple-linked list has an advantage when it comes to finding the ancestors of the nodes, such as finding the nearest public ancestor (LCA), which is irrelevant to the experiment.

It is worth noting that when a subtree of a node does not exist, the pointer field that points to that node should be NULL . One trick is that you can manually define a "null pointer field, " which should point to null when pointing to this so-called "empty Node", to some extent, to avoid the error of pointer access out of bounds.

Third, the design and implementation of the algorithm

The idea of this algorithm is very simple. This experiment can be divided into two parts-creating a two-fork tree and traversing a binary tree.

1. Create a two-fork tree (for example, first order sequence)

The sequence generation of a tree is a recursive process, so it is also necessary to recursively generate the tree as it iterates through the sequence.

Take the first order sequence as an example, if the current label is non-empty, then we get the current node data, after saving the data, the next data-whether the void node or the real data-is Zuozi data, so we will be recursive to record; If the current label is empty, that is, void node, meaning there is no node here , return NULL , The current node of the Zuozi recursive return to the right subtree recursion; Returns the address of the node, ending.

It can be seen that this is a process of simulating the sequence of the first sequence, looking at a node, the first access to the root node of the current subtree, then the left subtree, then the right subtree, and finally return.

Post order sequences can also be similarly generated, and the specifics will be mentioned below.

2, traverse the binary tree (take the middle sequence traversal as an example)

Similar to the creation of a tree, the traversal of a binary tree is also a recursive process.

Take the sequence traversal as an example, if the left dial hand tree is not empty, then recursively enter the left subtree; the label of the current node; if the right subtree is not empty, the right subtree is passed recursively; end. If you do not need the output sequence, but want this sequence, then it is natural to think of the stack, the output of the label to the operation of the label stack can be, other operations do not change.

Traversing a binary tree is significant, such as traversing a sorted binary tree in the middle sequence, and getting the ordered sequence of preservation.

Iv. expected results and problems in the experiment

1. Expected results:

The program can correctly generate the corresponding two-fork tree based on the input ordinal sequence (with the void node), and correctly output the sequence of sequential traversal. is an example of a three-order generation.

2, the problems in the experiment and some explanation:

(1) If there is no void node, can I get the only corresponding two-fork tree by three-order?

The answer is yes. The following is a brief description of how to get the corresponding two-fork tree using the ordinal sequence and the middle sequence sequence.

A) Analysis:

For an ordinal sequence, the first node must be the root node, and its right side is the first sequence of the Zuozi and then the first order sequence of the right sub-tree. The problem here is that we cannot find the dividing point of the left and right subtree sequences, in other words, we cannot get the corresponding two-fork tree by a sequence of first order.

Then we analyze the composition of the sequence, we can find the root node in the sequence (the label of the root node has been obtained in the sequence), the left side is the sequence of Zuozi, and the right is the middle sequence of the right subtree.

At this point we find that there is a substructure. Because the sequence length of a tree (subtree) is equal, so we can get the sequence of the left and right sub-tree, so for any subtree, we get its ordinal sequence and sequence, the problem is transformed into a similar sub-problem.

B) Achieve:

A) The first node of the first order sequence finds the root node;

b) found in the sequence of the node (here can be found sequentially, find the end can be, when the data is larger than the recommended method of binary search), the left and right sub-tree node number, so that the left and right sub-tree corresponding to the first sequence and sequence sequences;

c) recursive into the left and right sub-tree, respectively, build. The boundary of the recursion is the leaf node, its first order and the middle order are the length of 1 of their own label.

(2) How do sequence sequences containing void nodes generate a corresponding two-fork tree?

There is an easy way to scan sequential sequences from backward to forward, equivalent to the sequence generated by the "root node - right subtree - left dial hand tree" sequence. This is a mirror-like process that corresponds to a two-fork tree that is generated from an ordinal sequence, and is no longer mentioned.

(3) Can the sequence of sequences generate a unique two-fork tree?

The answer is in the negative. The ordinal sequence is not 1-1 corresponding to the two-fork tree , and is an example:

Both are legal two-fork trees, the sequence of the two is the CBA, even with the void node, the resulting sequence is $C $b$a$($ represents a space, That is, the void node), so the sequence of the middle sequence and the two-fork tree is not 1-1 corresponding, of course, can not be generated through the sequence of a unique two-fork tree.

(2) Can I not use recursive operation?

This problem can be attributed to the study of the nature of recursive operations.

A recursive operation is actually an operation on a stack, with an example of a first-order traversal of a binary tree: Press the current node to stack; If the left dial hand tree is not empty, the left subtree will be compressed, and if the right subtree is not empty, the right subtree will be compressed, and if the left and right subtrees are empty, that is, the current node is the leaf node, the stack, and when the nodes are left, the tree has finished the operation, the stack.

So we got an interesting result: all recursive algorithms can be implemented in a non-recursive way (the implementation of a non-recursive invocation here refers to a recursive call function, which is essentially recursive). Of course, also do not rule out some recursive solutions can also be solved by recursion, such as Hanoi Tower problem, here do not repeat.

Report:C + +Source code:

1 /*2 Project: Creating a two-fork tree, three-order traversal3 Zhang Yin4 */ 5#include <iostream>6#include <cstdio>7 8 using namespacestd;9 TenTemplate <classT>classBitree One { A Private: -T data;//the flag of the root node. -Bitree *lch, *rch;//left and right son the  Public: -     voidInitbitree ()//initialize a binary linked list -     { -data =0; +LCH = RCH =NULL; -     } +bitree* Creatbitree ()//First order (with void node) recursive establishment of two-fork linked list A     { atBitree <Char> *rt =NewBitree; -RT-Initbitree (); -         Charch; -scanf"%c", &ch); -         if(ch! =' ')//non-null pointers, recursive achievements -         { inRT-Data =ch; -RT-LCH =Creatbitree (); toRT-RCH =Creatbitree (); +         }  -         Else the         { *             DeleteRT; $RT =NULL;Panax Notoginseng         } -         returnRT; the     }  +     voidPreordertraverse ()//Recursive first-order traversal A     { theprintf"%c", data); +         if(LCH) -Lchpreordertraverse (); $         if(RCH) $Rchpreordertraverse (); -     } -     voidInordertraverse ()//Recursive middle order traversal the     { -         if(LCH)WuyiLchinordertraverse (); theprintf"%c", data); -         if(RCH) WuRchinordertraverse (); -     }  About     voidPostordertraverse ()//recursive post-sequential traversal $     { -         if(LCH) -Lchpostordertraverse (); -         if(RCH) ARchpostordertraverse (); +printf"%c", data); the     }  - }; $  the intMain () the { theBitree <Char> *Tree; the     //Tree-Initbitree (); -      inprintf"Please enter the first sequence of the binary tree, the nodes are denoted by letters, and the airspace is represented by spaces. \ n"); theTree = TreeCreatbitree (); the      Aboutprintf"First Order sequence: \ n"); theTreepreordertraverse (); theprintf"\ n"); the      +printf"ordinal sequence: \ n"); -Treeinordertraverse (); theprintf"\ n");Bayi      theprintf"Order sequence: \ n"); theTreepostordertraverse (); -printf"\ n"); -      the     return 0; the}
View Code

[Data structure] binary tree creation and traversal

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.