Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct Node {
- struct Node* lchild;
- int data;
- struct Node* rchild;
- }*root = NULL;
- void Insert(int key) {
- struct Node* t = root;
- struct Node* r = NULL, * p;
- if (root == NULL) {
- p = (struct Node*)malloc(sizeof(struct Node));
- p->data = key;
- p->lchild = p->rchild = NULL;
- root = p;
- return;
- }
- while (t != NULL) {
- r = t;
- if (key < t->data)
- t = t->lchild;
- else if (key > t->data)
- t = t->rchild;
- else
- return;
- }
- p = (struct Node*)malloc(sizeof(struct Node));
- p->data = key;
- p->lchild = p->rchild = NULL;
- if (key < r->data) r->lchild = p;
- else r->rchild = p;
- }
- void Inorder(struct Node* p) {
- if (p) {
- Inorder(p->lchild);
- printf("%d ", p->data);
- Inorder(p->rchild);
- }
- }
- struct Node* Search(int key) {
- struct Node* t = root;
- while (t != NULL) {
- if (key == t->data)
- return t;
- else if (key < t->data)
- t = t->lchild;
- else
- t = t->rchild;
- }
- return NULL;
- }
- int SearchPathLength(int key) {
- struct Node* t = root;
- static int counter = 0;
- while (t != NULL) {
- if (key == t->data)
- return counter;
- else if (key < t->data)
- {
- counter++;
- t = t->lchild;
- }
- else
- {
- counter++;
- t = t->rchild;
- }
- }
- return 0;
- }
- int Height(struct Node* p)
- {
- int x, y;
- if (p == NULL)return 0;
- x = Height(p->lchild);
- y = Height(p->rchild);
- return x > y ? x +1 : y + 1;
- }
- int main() {
- struct Node* temp;
- Insert(50);
- Insert(10);
- Insert(30);
- Insert(40);
- Insert(20);
- Inorder(root);
- printf("\n");
- temp = Search(20);
- if (temp != NULL)
- printf("element %d is found\n", temp->data);
- else
- printf("element is not found\n");
- int pathLevels = SearchPathLength(30);
- printf("The length is %d \n", pathLevels);
- printf("The height of the tree is %d \n", Height(root));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement