Provide the Next Siblings Pointers in a Given Binary Tree

Objective: – Given a binary tree with three pointers left, right and nextSibling). Write the program to provide the nextsibling pointers.

Example:

Provide the Next Siblings Pointers in a Given Binary Tree.

Provide the Next Siblings Pointers in a Given Binary Tree.

Approach:

  • Use Recursion.
  • Start from the root, if root’s left node is not null then make it point to the root’s right child.
  • check if root’s nextsibling is not null, if NOT then make the next sibling of root’s right node point to the root’s nextsibling’s left child. (In our example node 5 points node 6, as per our statement, Parent of node 5 is Node 2, next sibling of node 2 is node 3, and left child of node 2 is node 6, So Node 5 will points to Node 6 )

Code:



Output:

1
2 3
4 5 6 7

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

  • TopVideo Clips

    This code will fail, when node has only left or right child in each level.

%d bloggers like this: