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);}