Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions chapter_04/p04_check_balanced.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,37 @@ def test_is_balanced():
error_msg = f"{is_balanced.__name__} failed on {tree_gen.__name__}"
assert is_balanced(tree_gen()) == expected, error_msg

#Alternative Recursive Approach

# Balanced Tree
class Node():
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This class isn't used in the code anywhere and can thus be deleted.

def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right


def helper(root):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is too generic of a function name. Names should describe what the function does. In this case, _find_height would be a good name.

if root is None:
return 0
leftheight = helper(root.left)
if leftheight == -1:
return -1

rightheight = helper(root.right)
if rightheight == -1:
return -1

if abs(leftheight - rightheight) > 1:
return -1

return max(leftheight, rightheight) + 1

def isBalanced(root):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

function names in python should use underscore case (is_balanced)

return helper(root) > -1




if __name__ == "__main__":
test_is_balanced()