"Sword means offer" rebuilding binary tree

Source: Internet
Author: User

Title: Rebuilding a binary tree
To enter the results of the pre-order traversal and the middle sequence traversal of a binary tree, rebuild the two-fork tree. It is assumed that both the pre-order traversal of the input and the results of the middle-order traversal do not contain Dong numbers. For example, enter the pre-sequence traversal sequence {1,2,4,7,3,5,6,8} and the middle sequence traversal sequence {4,7,2,1,5,3,8,6}, then rebuild the two fork tree as shown and output its head node.
The binary tree nodes are defined as follows:
struct Binarytreenode{int m_nvalue; Binarytreenode *m_pleft; Binarytreenode *m_pright;};

Create the root node. The first data of the pre-sequence traversal is the data of the root node, the position of the root node is found in the middle sequence traversal, and the pre-order and the sequence traversal sequences of the right subtree of the Saozi are respectively known.

Binarytreenode *rebuiltbitree (int *preorder,int *inorder, int treenum) {if (preorder==null| | inorder==null| | treenum<=0) {return NULL;} The first number of the pre-order traversal is the root node Binarytreenode *root=new binarytreenode;root->m_nvalue=preorder[0];root->m_pright=root- >m_pleft=null;//The root node is found in the middle sequence traversal, the left node of the root node is the left subtree, the right node is the right subtree int rootorder=-1;for (int i=0; i<treenum; i++) {if (root->m _nvalue==inorder[i]) {rootorder=i;break;}} if (rootorder==-1) {printf ("Invalid Input");} Rebuild left subtree int treenumleft=rootorder;int *preorderleft=preorder+1;int *inorderleft=inorder;root->m_pleft= Rebuiltbitree (preorderleft,inorderleft,treenumleft);//rebuild Right subtree int treenumright=treenum-treenumleft-1;int * Preorderright=preorder+treenumleft+1;int *inorderright=inorder+treenumleft+1;root->m_pright=rebuiltbitree ( Preorderright,inorderright,treenumright); return root;}


"Sword means offer" rebuilding binary tree

Related Article

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.