Given a normal binary tree, convert it into a Left–child right–sibling (LC–RS) binary tree.

Each node in the LC–RS binary tree has two pointers: one to the node’s left child and one to its next sibling in the original binary tree. So starting with the root, each node’s leftmost child in the original tree is made its left child in the LC–RS binary tree, and its nearest sibling to the right in the original tree is made its right child in the binary tree. For example, we have a binary tree below:

 
LC–RS Binary Tree

 
(a) Processing binary tree to LC–RS binary tree, every node is linked and aligned with the left child, and the next nearest is a sibling.

(b) We can rewrite the binary tree shown by putting the left child node to one level below its parents and by placing the sibling next to the left child at the same level.

(c) We can transform this tree into a LC-RS binary tree by turning each sibling 45° clockwise.

Practice this problem

The idea is to traverse the tree in a postorder fashion and for every node,

  • If its left child is empty, then make its right child as left’s and set right to null.
  • If the left child already exists, then make the right child of its left child point to its right child and set the right child to null.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

1 2 4 5 3 6 7 8

Java


Download  Run Code

Output:

1 2 4 5 3 6 7 8

Python


Download  Run Code

Output:

1 2 4 5 3 6 7 8

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(h) for call stack, where h is the height of the tree.

 
References: Left–child right–sibling binary tree – Wikipedia