Binary tree algorithm: sequence and order derivation (array recursive implementation)

Source: Internet
Author: User

Reconstruction of binary tree with root sequence and posterior root sequence
Describe

We know how to travel around a binary tree in three depth priorities to get the root sequence, the previous root sequence, and the posterior root sequence. Conversely, if a binary tree is given the root sequence and the post root sequence, or given the root sequence and the previous root sequence, a one or two-fork tree can be reconstructed. The root sequence and the post root sequence of a binary tree are required to reconstruct the binary tree in memory, and finally the root sequence of the binary tree is output.

Each node of a binary tree is uniquely identified with a different integer, and the following two-tree

The root sequence is 9 5 32 67

Post-root sequence 9 32 67 5

Previous root sequence 5 9 67 32

First reading into a number n means that there are n elements in both the middle order and the post sequence.

Then enter the sequence of the middle sequence in the input sequence.

The output sequence of first order.

Input:

4

9 5 32 67

9 32 67 5

Output:

5 9 67 32

#include <stdio.h> #include <string.h>void build (int len, int *s1, int *s2, int *s) {    int p;    int i;    if (len<=0)        return;    else{for        (i=0; i<len; i++) {            if (s1[i]==s2[len-1]) {                p = i;            }        }        Build (p, S1, S2, s+1);        Build (Len-p-1, s1+p+1, S2+p, s+p+1);        S[0] = s2[len-1];}    } int main () {    int i;    int s1[1000], s2[1000], s3[1000];    int n;    while (scanf ("%d", &n)!=eof)    {for        (i=0; i<n; i++) {            scanf ("%d", &s1[i]);        }        for (i=0; i<n; i++) {            scanf ("%d", &s2[i]);        }        Build (n, s1, S2, S3);        for (i=0; i<n; i++) {            printf ("%d%c", S3[i], i==n-1? ' \ n ': ');        }    }    return 0;}

Binary tree algorithm: sequence and order derivation (array recursive implementation)

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.