-
Notifications
You must be signed in to change notification settings - Fork 1.9k
chapter 4--tree-- question 4 solution added to the bottom #224
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
- Loading branch information
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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(): | ||
| def __init__(self, value, left=None, right=None): | ||
| self.value = value | ||
| self.left = left | ||
| self.right = right | ||
|
|
||
|
|
||
| def helper(root): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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, |
||
| 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): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. function names in python should use underscore case ( |
||
| return helper(root) > -1 | ||
|
|
||
|
|
||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| test_is_balanced() | ||
There was a problem hiding this comment.
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.