Learn basic concept of c , c++ and python programming in regularcodes.com

Spread the post

Print all nodes at k distance from leaf

Write an efficient algorithm to print all binary tree node in k distance from all leaf nodes. Note K is an integer value.

Example

Suppose following nodes are inserted on binary tree.

13624578

Result

Hint: solve this problem by using a queue.

View nodes and pointers.

Stack Areamainhead(pointer) NULLroot(pointer)tail(pointer) NULL Heap Areastruct Treedata (int)= 1left (pointer) right (pointer) struct Treedata (int)= 2left (pointer) right (pointer) struct Treedata (int)= 3left (pointer)= NULLright (pointer) struct Treedata (int)= 4left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 5left (pointer) right (pointer)= NULLstruct Treedata (int)= 6left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 7left (pointer)= NULLright (pointer) struct Treedata (int)= 8left (pointer)= NULLright (pointer)= NULL

Try it Yourself

Program for print out all kth nodes from leaf of tree. using queue.


Output

Stack Areamainhead(pointer)root(pointer)tail(pointer)find_kthhead(pointer)k (int) =2print_nodecount (int) =0temp(pointer) Heap Areastruct Treedata (int)= 1left (pointer) right (pointer) struct Treedata (int)= 2left (pointer) right (pointer) struct Treedata (int)= 3left (pointer)= NULLright (pointer) struct Treedata (int)= 4left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 5left (pointer) right (pointer)= NULLstruct Treedata (int)= 6left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 7left (pointer)= NULLright (pointer) struct Treedata (int)= 8left (pointer)= NULLright (pointer)= NULLstruct Queuestatus (int)= 0link (pointer) parent (pointer)= NULLnext (pointer) struct Queuestatus (int)= 0link (pointer) parent (pointer) next (pointer) struct Queuestatus (int)= 0link (pointer) parent (pointer) next (pointer) struct Queuestatus (int)= 0link (pointer) parent (pointer) next (pointer) struct Queuestatus (int)= 0link (pointer) parent (pointer) next (pointer) struct Queuestatus (int)= 0link (pointer) parent (pointer) next (pointer) struct Queuestatus (int)= 0link (pointer) parent (pointer) next (pointer) struct Queuestatus (int)= 0link (pointer) parent (pointer) next (pointer)= NULL

Visualize process Try it Yourself

Spread the post

Recommended Posts: