Multi-tree and binary tree conversion, and binary tree Conversion

Source: Internet
Author: User

Multi-tree and binary tree conversion, and binary tree Conversion

-[Input :]

-Row 1: n (<= 300, node numbers in the tree are 1 to n)

-N rows below: I, j, And I Father j. The node with the parent node 0 is the root of the tree.

-[Output :]

-A Row outputs the result of the central traversal of the Binary Tree corresponding to the multi-tree, with a space between each two nodes.

-[Example input :]

-7

-2 1

-3 1

-4 1

-5 2

-6 2

-7 4

-1 0

-[Sample output :]

-7 4 3 6 5 2 1

First, this question shows the conversion rule between multi-tree and Binary Trees-left child and right brother. That is to say, the left child of any node of a binary tree converted from a multi-tree is its child in the original tree, and its right child node is its brother node in the original tree.

The left son of node 4 in the second tree is its child node in the first tree, and its right child 3 node is its brother node in the original tree.

So this question is very easy to do.

Input data n, indicating that there are n nodes.

In the next for loop, enter the node number and its parent node;

Use a struct to store trees.

Input edge conversion.

The final result of recursively traversing a binary tree in a central order.

The source code is as follows:

 #include
 
  const int maxn=10000;struct tree{int lson=0;int rson=0;};tree a[maxn];int tou;int bianli(int x){if(a[x].lson!=0){bianli(a[x].lson);}std::cout<
  
   <<' std::cin n,i,j; int { main() } bianli(a[x].rson); if(a[x].rson!="0)" ?;>>n;for(int z=1;z<=n;z++){std::cin>>i>>j;if(j==0) tou=i;else {if(a[j].lson==0){a[j].lson=i;}else {a[i].rson=a[j].lson;a[j].lson=i;}}}bianli(tou);}
  
 

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.