Given a binary tree, convert it into a full tree by removing half nodes (remove nodes having one child). A full binary tree is a tree in which every node other than the leaves has two children.

For example, the binary tree shown on the left should be converted into the binary tree shown on the right.

Convert binary tree into a full tree

Practice this problem

The idea is to traverse the tree in a bottom-up fashion and convert the left and right subtree before processing a node. Then for each node,

  • If it has two children or a leaf node, nothing needs to be done.
  • If it has exactly one child, delete it and replace the node with the child node.

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

C++


Download  Run Code

Output:

5 0 6 4 7

Java


Download  Run Code

Output:

5 0 6 4 7

Python


Download  Run Code

Output:

5 0 6 4 7

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