思路:
- 自上而下
分別找出A,B的路徑,然后尋找最短相同部分,最后一個node就是LCA。
(未經測試)
def lowestCommonAncestor(self, root, A, B):
# write your code here
path = []
self.final = []
path.append(root)
def dfs(root, target, path):
if root.left == None and root.right == None:
return
if root.left:
if root.left == target:
path.append(target)
self.final = path
return
else:
path.append(root.left)
dfs(root.left, target, path)
if root.right:
path.pop()
if root.right == target:
path.append(target)
return
else:
path.append(root.left)
dfs(root.left, target, path)
dfs(root, A, path)
path_A = self.final
dfs(root, B, path)
path_B = self.final
for i in range(0,len(path_B)):
if path_A[:i] != path_B[:i]:
return path_A[i-1]
- 自下而上
A,B 兩個點一定在LCA的兩個分支里,或者一個點在另一個點的分枝里。
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary search tree.
@param: A: A TreeNode in a Binary.
@param: B: A TreeNode in a Binary.
@return: Return the least common ancestor(LCA) of the two nodes.
"""
def lowestCommonAncestor(self, root, A, B):
# write your code here
if root == None or root == A or root == B:
return root
left = self.lowestCommonAncestor(root.left, A, B)
right = self.lowestCommonAncestor(root.right, A, B)
if left and right:
return root
else:
if left:
return left
else:
return right