Given two node, find the lowest common ancestor.
we build the test case here:
class ListNode:
def __init__(self,val):
self.val=val
self.next=None
class TreeNode:
def __init__(self,val):
self.val=val
self.left=None
self.right=None
root=TreeNode(0)
root.left=TreeNode(1)
root.right=TreeNode(2)
root.left.left=TreeNode(3)
root.left.right=TreeNode(4)
root.left.left.left=TreeNode(5)
root.right.left=TreeNode(8)
root.right.right=TreeNode(9)
based on the problem description there are two possible solutions:
1. with direction to parents:
we just need to trace back and mark nodes as visited. if the node is visited twice then we return the node.
2.without direction to parents:
we need to define a cover function first to see if the node exist in the subtree.
def covers(root,val):
if root==None:
return False
if root.val==val:
return True
return covers(root.left,val) or covers(root.right,val)
then we search the whole tree to see if they have LCA
def find(root,val1,val2):
if root==None:## if find the end still not return then None
return None
if root.val==val1 or root.val==val2:## if we find one of the node we return it and recurse
return root
v1left=covers(root.left,val1) ###if on the left
v2left=covers(root.left,val2)### if on the lelft
if v1left==v2left and v1left==True:## both of them on the left
return find(root.left,val1,val2)
if v1left==v2left and v1left==False:#right
return find(root.right,val1,val2)
if v1left!=v2left:# if not the same side we return
return root
def main():
if covers(root,5)==False or covers(root,4)==False:
return None
node=find(root,5,4)
print node.val
if __name__=="__main__":
main()