Showing posts with label level order. Show all posts
Showing posts with label level order. Show all posts

Friday, November 2, 2012

Binary Tree: level order linked list


Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists).

Approach:
We can do breadth first traversal of the tree keeping track of the levels, and create a linkedlist of all the nodes at any particular level

Input/Output:
iterative inorder:
3 7 9 15 17 21 25
printing level order:
15
7 21
3 9 17 25

Printing linked list at each level:
Level: 0
15
Level: 1
7 21
Level: 2
3 9 17 25

Sunday, February 19, 2012

Print nodes of a BST at a given depth on the same line.


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: 

3 10 
1 6 14 
4 7 13