题解 | #二叉搜索树的最近公共祖先#
二叉搜索树的最近公共祖先
https://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param root TreeNode类 # @param p int整型 # @param q int整型 # @return int整型 # class Solution: # 获取路径 def getPath(self, root:TreeNode, target: int): path = [] head = root while head.val != target: path.append(head.val) if head.val > target: head = head.left else: head = head.right path.append(head.val) return path def lowestCommonAncestor(self , root: TreeNode, p: int, q: int) -> int: p1 = self.getPath(root, p) q1 = self.getPath(root, q) i = 0 res = 0 while i < len(p1) and i < len(q1): if p1[i] == q1[i]: res = p1[i] i += 1 else: break return res
解题思路
解题思路:
- 先建立一个获取到某个值路径的函数;
- 然后根据这个函数分别获取p和q的路径;
- 最后,根据两者的路径,找到路径最后一个相同的元素即为最近公共祖先。
复杂度:
- 时间复杂度和空间复杂度都为O(N)。