Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- struct Node {
- int key;
- Node *left, *right;
- };
- // this function creates new node with number x and return the pointer to it
- Node *createNode(int x)
- {
- Node *newNode = new Node();
- newNode->key = x;
- newNode->left = NULL;
- newNode->right = NULL;
- return newNode;
- }
- // this function inserts node 'x' a tree rooted at 'root'
- // it will return root of the tree after update
- // so you must use it like this:
- // vvvvvvvvvvvvvvvvv
- // root = insert(root, x); -------- (*)
- // ^^^^^^^^^^^^^^^^^
- Node *insert(Node *root, int x)
- {
- if (root == NULL) // if empty, build a new node and return
- return createNode(x);
- // if exists, go left or go right
- if (x < root->key) {
- root->left = insert(root->left, x);
- // ^ this matches (*) pattern
- } else {
- root->right = insert(root->right, x);
- // ^ this matches (*) pattern
- }
- // don't forget to return original root after finishing
- return root;
- }
- void preorder(Node *root)
- {
- if (root == NULL) return;
- printf("%d ", root->key);
- preorder(root->left);
- preorder(root->right);
- }
- void postorder(Node *root)
- {
- if (root == NULL) return;
- postorder(root->left);
- postorder(root->right);
- printf("%d ", root->key);
- }
- void inorder(Node *root)
- {
- if (root == NULL) return;
- inorder(root->left);
- printf("%d ", root->key);
- inorder(root->right);
- }
- int main()
- {
- Node *root = NULL;
- root = insert(root, 5);
- root = insert(root, 10);
- root = insert(root, 3);
- root = insert(root, 7);
- preorder(root);
- printf("\n");
- postorder(root);
- printf("\n");
- inorder(root);
- printf("\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement