We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
fromcollectionsimportdequedeflca(root,v1,v2):ifrootisNone:returnNone# Find path from root to target nodedeffindPathToTarget(root,target_int):dq=deque([(root,[])])whiledq:node,path=dq.popleft()new_path=path+[node]#Createanewpathlistifnode.info==target_int:returnnew_pathifnode.left:dq.append((node.left,new_path))ifnode.right:dq.append((node.right,new_path))return[]# Get paths to v1 and v2path_to_v1=findPathToTarget(root,v1)path_to_v2=findPathToTarget(root,v2)# Compare paths to find LCAlca=Nonefora,binzip(path_to_v1,path_to_v2):ifa==b:lca=aelse:breakreturnlca
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Binary Search Tree : Lowest Common Ancestor
You are viewing a single comment's thread. Return to all comments →