C language to enter a binary search tree and convert the tree to its mirror
- 2020-04-02 02:44:52
- OfStack
The example of this article describes the C language to implement the input of a binary search tree and the tree into its mirror method, to share with you for your reference. The specific implementation method is as follows:
The recursive method is adopted to implement the code as follows:
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
struct Node {
Node(int i = 0, Node *l = NULL, Node *r = NULL) : item(i), left(l), right(r) {}
int item;
Node *left;
Node *right;
};
Node *Construct()
{
Node *node6 = new Node(11);
Node *node5 = new Node(9);
Node *node4 = new Node(7);
Node *node3 = new Node(5);
Node *node2 = new Node(10, node5, node6);
Node *node1 = new Node(6, node3, node4);
Node *root = new Node(8, node1, node2);
return root;
}
void Convert(Node *root)
{
if(root == NULL)
return;
Convert(root->left);
//Try swap(root-> Left, root -> Right),
//Looking at the output, it helps to understand binary tree recursion
Convert(root->right);
swap(root->left, root->right);
}
void InOrder(Node *root)
{
if(root) {
InOrder(root->left);
cout << root->item << " ";
InOrder(root->right);
}
}
void main()
{
Node *root = Construct();
InOrder(root);
cout << endl;
Convert(root);
InOrder(root);
}
It is hoped that the examples described in this paper will be helpful to the learning of C program algorithm design.