Skip to content

Commit

Permalink
Merge pull request #454 from Rashigera/feature/balancedBinTree
Browse files Browse the repository at this point in the history
check if a tree is balanced or not #419
  • Loading branch information
UTSAVS26 authored Nov 8, 2024
2 parents ba118b2 + 168b958 commit f95d303
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
54 changes: 54 additions & 0 deletions Algorithms_and_Data_Structures/balancedBinTree/balancedBinTree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Node class for the binary tree
class Node:
def __init__(self, val): # Changed from init to __init__
self.data = val
self.left = None
self.right = None

class Solution:
# Function to check if a binary tree is balanced
def isBalanced(self, root):
return self.dfsHeight(root) != -1

# Recursive function to calculate the height of the tree
def dfsHeight(self, root):
# Base case: if the current node is None, return 0 (height of an empty tree)
if not root:
return 0

# Recursively calculate the height of the left subtree
left_height = self.dfsHeight(root.left)

# If the left subtree is unbalanced, propagate the unbalance status
if left_height == -1:
return -1

# Recursively calculate the height of the right subtree
right_height = self.dfsHeight(root.right)

# If the right subtree is unbalanced, propagate the unbalance status
if right_height == -1:
return -1

# Check if the difference in height between left and right subtrees is greater than 1
if abs(left_height - right_height) > 1:
return -1

# Return the maximum height of left and right subtrees, adding 1 for the current node
return max(left_height, right_height) + 1


# Creating a sample binary tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right
#Creating an instance of the Solution class
solution = Solution()

# Checking if the tree is balanced
if solution.isBalanced(root):
print("The tree is balanced.")
else:
print("The tree is not balanced.")
2 changes: 2 additions & 0 deletions Project-Structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,8 @@
* [Symmetric Tree](Algorithms_and_Data_Structures/Trees/Symmetric_Tree.py)
* Avl Tree Visualizer
* [Main](Algorithms_and_Data_Structures/avl_tree_visualizer/main.py)
* Balancedbintree
* [Balancedbintree](Algorithms_and_Data_Structures/balancedBinTree/balancedBinTree.py)
* Bellman Ford
* [Bellman Ford](Algorithms_and_Data_Structures/bellman_ford/Bellman_ford.py)
* Closest Pair Of Points
Expand Down

0 comments on commit f95d303

Please sign in to comment.