Showing posts with label linked list. Show all posts
Showing posts with label linked list. 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

Tuesday, February 21, 2012

Detect loop in a singly linked list.

Write code to detect a loop in a linked list.


Approach:
Keep 2 pointers at the head, say front and back.
Now move the front twice the speed as the back, if before back completing the one loop, the front pointer reaches back or overtakes it then there is loop in the singly link list.