Write code to print out a binary search tree, such that all nodes at a given depth are printed on the same line.
Approach:
This problem is basically asking us to do the breadth First Search of the BST, such that all the nodes at a particular level are printed in new line.
Have a queue data structure.
init by adding root node ie 8 in the queue, then add a marker node which contains "null" elements.
when we dequeue any element from the queue, if its a normal node in the binary search tree then print it and add its not null left & right nodes to queue.
If we get a marker node then print a new line and add it back again to the queue if its not empty.
Code input and output:
int [] A = {8, 3, 10, 1, 6, 14, 4, 7, 13};
Printing inorder recursively:
1 3 4 6 7 8 10 13 14
Printing level order traversal of BST:
8
3 10
1 6 14
4 7 13
No comments:
Post a Comment