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

Spread the post

Check if two nodes are cousins in binary tree

Write an efficient algorithm to find that given two binary nodes are cousin or not.

Condition of cousin nodes.

1) nodes are exist in same level.

2) parent nodes are not same at given nodes.

Example

Suppose following nodes are inserted on binary tree.

13682574

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) struct Treedata (int)= 7left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 8left (pointer)= NULLright (pointer)= NULL

Try it Yourself

Program for check if two given nodes are cousins in binary tree. iterative solution using queue.


Output

Stack Areamainhead(pointer)root(pointer)tail(pointer)check_cousinauxiliary(pointer)first (int) =8second (int) =9temp1(pointer) NULLtemp2(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) struct Treedata (int)= 7left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 8left (pointer)= NULLright (pointer)= NULLstruct Queueheight (int)= 0link (pointer) next (pointer) struct Queueheight (int)= 1link (pointer) next (pointer) struct Queueheight (int)= 1link (pointer) next (pointer) struct Queueheight (int)= 2link (pointer) next (pointer) struct Queueheight (int)= 2link (pointer) next (pointer) struct Queueheight (int)= 2link (pointer) next (pointer) struct Queueheight (int)= 3link (pointer) next (pointer) struct Queueheight (int)= 3link (pointer) next (pointer)= NULL

Visualize process Try it Yourself

Spread the post

Recommended Posts: