Here, is code of in - order traversal in binary search tree with using recursive method.
All you have to do is follow these steps:
All you have to do is follow these steps:
1) Create an empty stack S. 2) Initialize current node as root
Here starts our loop, 3) Push the current node to S and set current = current->left until current is NULL
4) If current is NULL and stack is not empty then a) Pop the top item from stack. b) Print the popped item, set current = current->right c) Go to step 3. 5) If current is NULL and stack is empty then we are done.
#include<stdio.h> #include<iostream> using namespace std; struct node { int val; node *left; node *right; }*root; void make_tree(node **temp,int i) { if((*temp) == NULL) { (*temp) = new node; (*temp)->val = i; (*temp)->right = (*temp)->left = NULL; } else if((*temp)->val > i) { make_tree(&(*temp)->left,i); } else { make_tree(&(*temp)->right,i); } } void in_order(node *temp) { node *stk[500]; int index = 0; stk[index] = temp; temp = temp->left; while(temp || index != -1) { if(temp != NULL) { stk[++index] = temp; temp = temp->left; } else { temp = stk[index--]; cout<<temp->val<<"\t"; temp = temp->right; } } cout<<"\n"; } int main() { int n,i; cin>>n; while(n--) { cin>>i; make_tree(&root,i); } cout<<"In - Order Traversal : "; in_order(root); return 0; }
No comments:
Post a Comment
Your comment is valuable to us