难度:简单
题目描述:
思路总结:
难者不会,做过就不难。利用二叉搜索树的性质,左子树<根节点<右子树。根据经验可以得到,如果p和q不再当前结点的某一子树里,(二叉搜素树性质,同时大于,或者同时小于。)就是最近公共祖先。
题解一:(递归)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
#思路:
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
if p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
return root
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
#思路:
stack = [root]
while stack:
cur = stack.pop()
if p.val < cur.val and q.val < cur.val:
stack.append(cur.left)
elif p.val > cur.val and q.val > cur.val:
stack.append(cur.right)
else:
return cur
#改进后
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
#思路:
node = root
while node:
if p.val < node.val and q.val < node.val:
node = node.left
elif p.val > node.val and q.val > node.val:
node = node.right
else:
return node