|
| 1 | +import unittest |
| 2 | + |
| 3 | +from problems.tree.lowest_common_ancestor_of_a_binary_search_tree import LowestCommonAncestorOfABinarySearchTree |
| 4 | +from problems.util.tree_node import TreeNode |
| 5 | + |
| 6 | + |
| 7 | +class LowestCommonAncestorOfABinarySearchTreeTest(unittest.TestCase): |
| 8 | + # noinspection PyTypeChecker |
| 9 | + def test_lowest_common_ancestor(self): |
| 10 | + lowest_common_ancestor_of_a_binary_search_tree = LowestCommonAncestorOfABinarySearchTree() |
| 11 | + |
| 12 | + # Test case 1: Both nodes are null |
| 13 | + self.assertIsNone(lowest_common_ancestor_of_a_binary_search_tree.lowestCommonAncestor(None, None, None)) |
| 14 | + |
| 15 | + # Test case 2: One node is null |
| 16 | + root = TreeNode(3) |
| 17 | + p = TreeNode(1) |
| 18 | + self.assertIsNone(lowest_common_ancestor_of_a_binary_search_tree.lowestCommonAncestor(root, None, p)) |
| 19 | + self.assertIsNone(lowest_common_ancestor_of_a_binary_search_tree.lowestCommonAncestor(root, p, None)) |
| 20 | + |
| 21 | + # Test case 3: Both nodes are the same |
| 22 | + self.assertEqual(lowest_common_ancestor_of_a_binary_search_tree.lowestCommonAncestor(p, p, p), p) |
| 23 | + |
| 24 | + # Test case 4: LCA is root |
| 25 | + q = TreeNode(5) |
| 26 | + root.left = p |
| 27 | + root.right = q |
| 28 | + self.assertEqual(lowest_common_ancestor_of_a_binary_search_tree.lowestCommonAncestor(root, p, q), root) |
| 29 | + |
| 30 | + # Test case 5: LCA is in the left subtree |
| 31 | + p2 = TreeNode(0) |
| 32 | + p.left = p2 |
| 33 | + self.assertEqual(lowest_common_ancestor_of_a_binary_search_tree.lowestCommonAncestor(root, p2, p), p) |
| 34 | + |
| 35 | + # Test case 6: LCA is in the right subtree |
| 36 | + q2 = TreeNode(6) |
| 37 | + q.right = q2 |
| 38 | + self.assertEqual(lowest_common_ancestor_of_a_binary_search_tree.lowestCommonAncestor(root, q, q2), q) |
| 39 | + |
| 40 | + # Test case 7: Complex tree |
| 41 | + root2 = TreeNode(6) |
| 42 | + p3 = TreeNode(2) |
| 43 | + q3 = TreeNode(8) |
| 44 | + root2.left = TreeNode(0) |
| 45 | + root2.right = TreeNode(4) |
| 46 | + root2.left.left = TreeNode(3) |
| 47 | + root2.left.right = TreeNode(5) |
| 48 | + self.assertEqual(lowest_common_ancestor_of_a_binary_search_tree.lowestCommonAncestor(root2, p3, q3), root2) |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == '__main__': |
| 52 | + unittest.main() |
0 commit comments