Given a binary tree, check if removing an edge can split it into two binary trees of equal size.

For example, removing the edge 1 —> 2 from a binary tree on the left below splits it into two binary trees of size 3. However, there is no edge whose removal splits the binary tree on the right into two equal-size binary trees.

Remove Edge from a Binary Tree

Practice this problem

The idea is to count the total number of nodes n in the binary tree and traverse the binary tree to find the size of subtree m rooted at each node. The binary tree can be split if n is even, and the relation 2×m=n holds for at least one node in the binary tree.

Following is the implementation of this approach in C++, Java, and Python:

C++


Download  Run Code

Output:

The binary tree can be split

Java


Download  Run Code

Output:

The binary tree can be split

Python


Download  Run Code

Output:

The binary tree can be split

The time complexity of this approach is O(n2), 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.

 
We can easily solve the problem in O(n) time by doing a postorder traversal on the binary tree. Instead of calculating the left and right subtree size for every node in the tree, get the size in O(1) time in a bottom-up fashion.

The idea is to start from the bottom of the tree and return the size of the subtree rooted at the given node to its parent. The size of a subtree rooted at any node is one more than the sum of the left and right subtree size. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The binary tree can be split

Java


Download  Run Code

Output:

The binary tree can be split

Python


Download  Run Code

Output:

The binary tree can be split

Exercise Extend the solution to print the edge involved in splitting a binary tree.