Rebuilding a binary tree

Source: Internet
Author: User

Title: Re-Restoring a two-fork tree based on First order traversal and middle sequence traversal

Ideas:

1. Find the first number in the first order and assign it to the root node root->data;

2. Find the first number in the ordinal sequence;

3. The sequence to the left of the middle sequence is the root node Zuozi (left recursion), and the right side of the sequence is root (right recursion).

The code is as follows:

#include <iostream>using namespacestd;structtreenode{intdata; Treenode*Lchild; Treenode*rchild;};//Rebuilding a binary tree: recursive constructionTreenode *build (int*first,int*second,intlength) {    //determine if the parameters are legitimate    if(first==null| | second==null| | length<=0)        returnNULL; introotvalue=first[0]; Treenode*root=NewTreenode (); Root->data=Rootvalue; Root->lchild=root->rchild=NULL; //only one node is returned.    if(length==1)    {        if(first[0]==second[0])            returnRoot; Else            Throwexception"input error!");//throws an exception, in C # is the throw new Exception ();    }    //recursive at multiple nodes.    Else    {        intI=0; //finding the root node in the middle sequence traversal         while(i<length&&second[i]!=rootvalue) I++; if(i==length)Throwexception"input error!!"); //recursive left sub-tree, I left sequence        if(i>0) {root->lchild=build (first+1, Second,i); }        //Recursive right sub-tree, I right-hand sequence        if(i<length-1) {root->rchild=build (first+i+1, second+i+1, length-i-1); }    }    returnRoot;}//Print binary tree by middle ordervoidPrint (Treenode *root) {    if(root) {print (Root-lchild); cout<<root->data<<Endl; Print (Root-rchild); }}intMain () {Try    {        inta[Ten]={1,2,4,7,3,5,6,8}; intb[Ten]={4,7,2,1,5,3,8,7}; Treenode*root=build (A, B,8);    print (root); }    Catch(ConstException &e) {Cerr<<e.what () <<endl;//Cerr used to output exceptions    }}

Test results:

Rebuilding a binary 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.