Created
February 28, 2012 22:40
-
-
Save simong/1935779 to your computer and use it in GitHub Desktop.
U Suck at coding 2012-02-28
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python | |
| class Node(object): | |
| left = None | |
| right = None | |
| value = None | |
| def __init__(self, val): | |
| self.value = val | |
| class Tree(object): | |
| root = None | |
| def __init__(self): | |
| root = Node(None) | |
| def compare(a, b): | |
| """ Assuming a and b are both Node objects (or None), compare them. """ | |
| if a and b: | |
| # Both a and b are actual objects. | |
| # Compare their values and recursively their children. | |
| return a.value == b.value and compare(a.left, b.left) and compare(a.right, b.right) | |
| else: | |
| # Both a and b should be None in order to be 'equal'. | |
| return a == b | |
| def build_tree(): | |
| t = Tree() | |
| t.root = Node("A") | |
| t.root.left = Node("D") | |
| t.root.right = Node("C") | |
| t.root.left.left = Node("B") | |
| return t | |
| def main(): | |
| # 2 identical trees. | |
| t1 = build_tree() | |
| t2 = build_tree() | |
| # Random tree. | |
| t3 = Tree() | |
| t3.value = "D" | |
| t3.right = Node("A") | |
| assert compare(t1.root, t2.root) | |
| assert not compare(t1.root, t3.root) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment