def contain(root: TreeNode, findNode: TreeNode): return TreeUtil.findNodeByVal(root, findNode.val)
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode: def contain(root: TreeNode, findNode: TreeNode): return TreeUtil.findNodeByVal(root, findNode.val) def getCommonAncestor(node: TreeNode): if node is p: if contain(node, q): return node return None elif node is q: if contain(node, p): return node return None if contain(node.left, p): if contain(node.right, q): return node return getCommonAncestor(node.left) elif contain(node.left, q): if contain(node.right, p): return node return getCommonAncestor(node.right) return getCommonAncestor(root) # root = TreeUtil.createBinaryTree([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4]) root = TreeUtil.createBinaryTree([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4]) print(Solution().lowestCommonAncestor(root, TreeUtil.findNodeByVal(root, 5), TreeUtil.findNodeByVal(root, 4)).val)