从顶至下,依次获取等于 p 或者 等于 q 的节点值,如果不相等返回空,若 p 或 q 存在于当前节点 root 的左子树和右子树中,则返回当前节点,否则返回左子树和右子树中有值的节点 root.left 或 root.right
# 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 lowestCommonAncestor(self , root: TreeNode, p: int, q: int) -> int:
# write code here
r = self.lowest_ancestor(root, p, q)
if r:
return r.val
return -1
def lowest_ancestor(self, root: TreeNode, p: int, q: int) -> TreeNode:
if not root or root.val == p or root.val == q:
return root
l = self.lowest_ancestor(root.left, p, q)
r = self.lowest_ancestor(root.right, p, q)
if l and r:
return root
elif l:
return l
else:
return r