1119 Pre- and Post-order Traversals (the sequence preorder + = binary tree)

Topic: https://pintia.cn/problem-sets/994805342720868352/problems/994805353470869504

Subject to the effect:

A given number of tree nodes n, and its front and rear sequence preorder traversal, in order traversal its output, if the preorder No outputs are not unique, and wherein one of the output sequence can, if the only inorder traversal outputs Yes, and outputs it in the sequence.

analysis:

Judgment basis, if a node of a binary tree or left subtree right subtree is empty, can not be uniquely determined according to its binary tree preorder and postorder.

How to order according to the current and subsequent to find the root of it?

First, a reciprocal of the first and the subsequent first preamble are equal, this node is the root node.

Then, after traversing the penultimate node for the right subtree root node (assuming a right subtree is always present) , and to find the location thereof with the root of the prior order, if the root node is left without a node, it shows that the current root is not left subtree, i.e., the binary tree can not be uniquely determined, and divided by the root node left, right subtree first order sequence and the left, rear right subtree motif sequences, recursive processing.

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 
 5 vector<int> pre,in,post;
 6 
 7 bool unique = true;
 8 void create(int preL,int preR,int postL,int postR) {
 9     if(preL == preR) { //叶子结点
10         in.push_back(pre[preL]);
11         return ;
12     }
13     // Find the next root sequence preceding position in the sequence 
14      int K + = preL . 1 , leftNum;
 15      the while (K <= PreR && pre [K] = POST [postR-! . 1 ]) K ++ ;
 16      leftNum = preL--K . 1 ;
 . 17      IF (K - preL> . 1 ) // if the next left subtree root exists 
18 is          Create (preL + . 1 , preL + leftNum, Postl, Postl + leftNum- . 1 );
 . 19      the else  / / left subtree does not exist, is not unique binary tree 
20 is          uNIQUE = to false ;
 21 is      in .push_back (pre [preL]);
 22 is     create(preL+leftNum+1,preR,postL+leftNum,postR-1);
23 }
24 
25 int main() {
26     int n;
27     cin>>n;
28     pre.resize(n);
29     post.resize(n);
30     for(int i = 0; i < n; ++i) cin>>pre[i];
31     for(int i = 0; i < n; ++i) cin>>post[i];
32     create(0,n-1,0,n-1);
33     if(unique) printf("Yes\n");
34     else printf("No\n");
35     for(int i = 0; i < in.size(); ++i) {
36         if(i > 0) printf(" ");
37         printf("%d",in[i]);
38     }
39     printf("\n");
40     return 0;
41 }

 

Guess you like

Origin www.cnblogs.com/keep23456/p/12556726.html