HDU 1710:binary Tree traversals

Source: Internet
Author: User

A sequence of sequential and sequential traversal sequences of two-forked trees is given, and the sequence of the two-forked tree is obtained.


In order traversal, the first must be the root node, and then the next node in the first order traversal is on the left or right side of the root node in the middle sequence traversal, the left node is in the left subtree of the root junction, and the right is in the right subtree. Depending on which side of the root junction the node looks for on that side, if there is no node on that side, add the node to it, or continue looking for the root node with that node until you build a complete binary tree. Finally, the output binary tree is traversed by post-post.


Code:

#include <cstdio> #include <cstring> #include <iostream> using namespace std;
    struct node{int num;
    Node *l,*r;

node (int x): num (x), L (null), R (null) {}};
int n;

int dlr[1005],ldr[1005];
    void Insert (node *h,int x) {bool flag=0;
        for (int i=0;i<n;i++) {if (ldr[i]==h->num) flag=1;
    if (ldr[i]==x) break;
            } if (!flag) {if (h->l==null) {Node *n=new node (x);
            h->l=n;
        Return
    } else Insert (H-&GT;L,X);
            } else {if (h->r==null) {Node *n=new node (x);
            h->r=n;
        Return
    } else Insert (H-&GT;R,X);
    }} void Postorder (node *h) {if (h->l!=null) postorder (h->l);
    if (h->r!=null) postorder (h->r); printf ("%d%s", H->num, ((--n) ==0)? "

\ n ":");}
    int main () {//freopen ("In.txt", "R", stdin);
        while (Cin>>n) {for (int i=0;i<n;i++) cin>>dlr[i]; for (int i=0;i<n;i++) cin>>ldr[i];
        Node h (dlr[0]);
        for (int i=1;i<n;i++) {insert (&h,dlr[i]);
    } postorder (&h);
} return 0;
 }


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.