Graph theory and its application--tree

Source: Internet
Author: User

In the previous introductory diagram article, we learned that graph is an abstract representation of the relationship between things, and based on the concept of graphs, we take out all the non-loop graphs and give them a new name-the tree.
There are a lot of conceptual terms about trees, so let's start with a simple two-fork tree (a root with up to two subtrees) for analysis.


This is some simple two-fork tree, where a, B, C and so on we become nodes. A is called the root node, its two branches are B and C, and we call B is a left subtree, C is a right sub-tree, knowing these simple concepts, we can initially explore some of the problems.

Binary tree as a special kind of graph, we should also study the way of its traversal, as we study the general graph of the way of traversal. Because its basic structure includes root, Zuozi, right subtree, we can change the output of these three elements to get different traversal order when we traverse.
Recursive definition of a pre-order traversal: For a node, access and output the root information, traverse the left subtree according to the preamble, and traverse the right subtree according to the preamble.
Recursive definition of Middle sequence traversal: For a node, traverse the left subtree according to the middle order, access the information of the output root, and traverse the right subtree according to the middle order.
Recursive definition of post-order traversal: For a node, follow the next step to traverse the left subtree, and follow the order to traverse the right subtree; Access and output the root information.
Take d For example, the pre-sequence traversal: 124536,; Middle sequence traversal: 425361; post-order traversal: 452631.
It is worth noting that, in addition to the sequence traversal, the other two traversal methods can be generalized to K-fork tree, because for the middle sequence traversal, every time the left dial hand tree, will access the root node, which will cause multiple repeated access to the root node, there is no "traversal" of the two words.
And for a given pre (post) sequence traversal and the middle sequence traversal of the two-tree, can be uniquely determined.

So let's look at a question about the three kinds of traversal of the binary tree (problem source:pku2255)

Description

Little Valentine liked playing with binary trees very much.  Her favorite game is constructing randomly looking binary trees with capital letters in the nodes. This is a example of one of her creations:
                                               D                                               /                                               /                                                B     E                                            /\                                                /   \                                               A     C     G                                                     /                                                    /                                                   F
To record hers trees for the future generations, she wrote down the strings for each tree:a preorder traversal (root, left Sub Tree, right subtree) and a inorder traversal (left subtree, root, right subtree).  For the tree drawn above the preorder traversal are DBACEGF and the inorder traversal is ABCDEFG. She thought that such a pair of strings would give enough information to reconstruct the tree later (but she never tried I T).
Now, years later, looking again in the strings, she realized that reconstructing the trees is indeed possible, but only B  Ecause she never had used the same letter twice in the same tree.  However, doing the reconstruction by hand, soon turned off to be tedious. So now she asks you to write a program this does the job for her!

Input

The input would contain one or more test cases. Each test case consists of one line containing the strings Preord and Inord, representing the preorder traversal and Inord ER traversal of a binary tree. Both strings consist of unique capital letters. (Thus they is not longer than characters.) Input is terminated by end of file.

Output

For each test case, recover Valentine's binary tree and print one line containing the tree's Postorder traversal (left Sub Tree, right subtree, root).


The main topic: Give a binary tree of the pre-sequence traversal, the middle sequence traversal, let you output its post-order traversal.

Mathematical analysis: According to its definition, three kinds of traversal methods are generated by recursion, then now know the two ways of traversal, but also can restore the original two-fork tree.
For example, taking the first set of data, the pre-order traversal is DBACEGF, the middle sequence traversal is ABCDEFG, then we through the definition of the pre-order traversal, we know that D is the largest tree root, at this time we then through the middle sequence traversal, ABC on the left side of D, is the left subtree, and EFG in D right side, the right This allows you to draw a tree initially. Then we are looking for the second point of the pre-order traversal ... In the end, the original two-fork tree must be restored.

Here the topic requires direct output after the post-traversal, then we restore the binary tree at the same time can also construct a post-sequential traversal. In the starting situation, the first point of the pre-sequence traversal as the root of the whole tree is to be used as the last point of the post-order traversal, which is we then through the middle sequence traversal and pre-sequence traversal to find the right subtree under this root, we see the right subtree as a whole, through the pre-sequence traversal can find a root, and then through this root and Saozi right sub-tree ... Until this root has no subtree.
The left sub-tree is then constructed.
This is the first to find the root and then find the right sub-tree looking for left dial hand tree, and the post-traversal recursive concept echoes.

Programming implementation: Through the above description, the construction process is essentially a recursive, but also can be said to traverse the map we are familiar with the deep search.

The reference code is as follows.

#include <iostream>#include<string.h>using namespacestd;Charpreorder[ -];Charmidorder[ -];Charpostorder[ -];intLen;voidTravelintPrestar,intPreend,intMidSTAR,intmidend) {       if(Prestar > Preend)return; postorder[--len] = Preorder[prestar];//Record Root       if(Prestar = = preend)return; inti;  for(i =0; I <= midend;i++)         if(Midorder[i] = =Preorder[prestar]) Break; Travel (Prestar+ I-midstar +1, Preend, i +1, midend);//left dial hand treeTravel (Prestar +1, Prestar + I-midstar, MidSTAR, I-1);//Right sub-tree }intMain () { while(cin>>preorder>>Midorder) {Len=strlen (preorder); Postorder[len]=' /'; Travel (0, len-1,0, len-1); cout<< postorder<<Endl; }}


Here we will describe some of the other applications of tree structure in storing information.

First we introduce the line segment tree.
Line tree, as the name implies, must be related to the line segment, we use a line segment [1,n] The integer points on the storage of information, and then the binary method to form a complete binary tree to store this information, and can also be accessed to find, update data and other operations, in the subsequent analysis of the specific problems we will discuss.
Line tree can solve a lot of problems, here we start from a simple problem to learn from the line segment tree-the maximum value of the specified interval. (Problem source:hdu1754)

Problem description Many schools are popular for a comparative habit. Teachers like to ask, from XXX to XXX, the highest score is how much. This makes many students very disgusted.
Whether you like it or not, now you need to do is to follow the teacher's request, write a program, mock teacher's inquiry. Of course, teachers sometimes need to update a student's grades. Input This topic contains multiple sets of tests, please handle to the end of the file. On the first line of each test, there are two positive integers N and M (0<n<=200000,0<m<5000), which represent the number of students and the number of operations respectively. Student ID numbers are numbered from 1 to N, respectively. The second line contains n integers representing the initial scores of the N students, of which the number of I represents the student's score for ID i. Then there's M-line. Each line has a character C (only ' Q ' or ' U '), and two positive integers, A/b. When C is ' Q ', it indicates that this is a query operation, which asks for the highest number of students whose IDs are from a to B (including A, a). When C is ' U ', it indicates that this is an update operation that requires the student with ID A to change the grade to B. Output outputs the highest score in a row for each query operation.


The topic is very clear, mathematical analysis is not difficult, then here we focus on the implementation of its programming.
We first divide the whole problem into functional, then consider the realization of the function modularization. In the above problem, we want to complete the storage of data, access to data to get the maximum value, update data.
Here perhaps people will consider directly using the array to record and then traverse to find the maximum, but this method, first, the violence is too high time complexity, second, this method is difficult to complete the data update. So here we consider constructing a line tree.
Storage of data: That's what we call building a tree. Here we will construct the binary search (DFS) and record the maximum value of its Saozi right subtree at each non-leaf node, which is achieved by deep searching and backtracking. At this point, if we consider the N person's score as the "carrying" of the integer on the line segment [1,n], then each non-leaf node records the maximum value on the interval segment when the whole tree is constructed.
Access to the data to get the maximum: here we still need to use a binary search idea, and then match the interval with the information we have constructed to record the segment tree to get the answer.
Update data: Here is still based on the binary search (because the structure of the segment tree is used when the dichotomy, which we construct the line segment is essentially a complete binary tree is echoed), once found in the leaf node, the data is updated, and then the same as the work of the retrospective operation of the entire book node to be updated again.

With the above analysis of the programming process, it is not difficult to understand the code.
The reference code is as follows. (>> and << operation in the code, nothing more than/2 or * * *, here is to get the line segment tree in the corresponding array subscript, the reader a little simulation to know why the code is so written).

#include <cstdio>#include<cmath>using namespacestd;intmax[4000001];intMaxintAintb) {     returnA>b?a:b;}voidPushup (intIndex//backtracking constructs a segment tree{Max[index]= Max (max[index<<1],max[(index<<1)+1]);}voidBuildintLintRintIndex//Create a line segment tree{     if(L = =r) {scanf ("%d",&Max[index]); return; }     intm = (L + r) >>1; Build (L,m,index<<1); Build (M+1, R, (index<<1)+1); Pushup (index);}voidUpdateintPintQintLintRintIndex//Update Data{    if(L = =R) {Max[index]=Q; return; }    intm = (r+l) >>1; if(P <=m) Update (P,q,l,m,index<<1); ElseUpdate (P,q,m+1, R, (index<<1)+1); Pushup (index);}intGetmax (intLintRintLintRintIndex//access to data for a given interval{     if(L<=l && R >=R)returnMax[index]; intm = (r+l) >>1; intRET =0; if(L <=m) Ret= Max (Ret,getmax (l,r,l,m,index<<1)); if(R >m) Ret= Max (Ret,getmax (l,r,m+1, R, (index<<1)+1)); returnret;}intMain () {intN, M, a, B, I; CharC;  while(SCANF ("%d%d", &n,&m)! =EOF) {Build (1N1);  for(i =0; I < m;i++) {scanf ("%*c%c%d%d",&c,&a,&b); if(c = ='Q') printf ("%d\n", Getmax (A, B,1N1)); ElseUpdate (A, B,1N1); }     }}

Graph theory and its application--tree

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.