VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halves/

⇱ Check if removing an edge can divide a Binary Tree in two halves - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if removing an edge can divide a Binary Tree in two halves

Last Updated : 26 Oct, 2024

Given a Binary Tree, the task is to find if there exists an edge whose removal creates two trees of equal size.

Examples:

Input:

👁 check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halvesb

Output : True
Explanation: Removing edge 5-6 creates two trees of equal size.

Input:

👁 check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halvesa

Output : False
Explanation: There is no edge whose removal creates two trees of equal size.

[Naive Approach] Recursive Method - O(n^2) Time and O(h) Space

The idea is to count the number of nodes in the tree. Let count of all nodes be n. Traverse the tree again and for each node, find size of subtree rooted with this node. Let cnt be the size of subtree size. If n-cnt is equal to cnt, then return true. Otherwise recursively check for left and right subtree.

Below is the implementation of the above approach:


Output
True

[Expected Approach] Bottom-Up Manner - O(n) Time and O(h) Space

The idea is to traverse tree in bottom up manner and while traversing, for each node, find the size of the subtree and check if the current node follows the required property.

Below is the implementation of above approach:


Output
True
Comment
Article Tags:
Article Tags: