Question : Write a function for in-order traversal of nodes in the range x to y from a binary search tree.
This is quite a simple function. As a first solution we can just traverse our binary search tree in inorder and display only the nodes which are in the range x to y.
But if the current node has a value less than x, do we have to traverse its left subtree? No. Because all the nodes in left subtree will be smaller than x.
Similarly if the current node has a key value more than y, we need not visit its right subtree.
Now we are ready to write our algorithm.
That's all. We have our function ready.This is quite a simple function. As a first solution we can just traverse our binary search tree in inorder and display only the nodes which are in the range x to y.
But if the current node has a value less than x, do we have to traverse its left subtree? No. Because all the nodes in left subtree will be smaller than x.
Similarly if the current node has a key value more than y, we need not visit its right subtree.
Now we are ready to write our algorithm.
- if nd is NOT NULL
- if nd->val >=x then
- visit all the nodes of left subtree of nd recursively
- display nd->val
- if nd->val <y then
- visit all the nodes of right subtree of nd recursively
void in_order_middle(NODEPTR nd,int x, int y) { if(nd) { if(nd->val >=x) in_order_middle(nd->left,x,y); if(nd->val>=x && nd->val<=y) printf("%d ",nd->val); if(nd->val <=y) in_order_middle(nd->right,x,y); } }
Comments
Post a Comment