解法1:未使用二叉树特性,暴力递归,会超出迭代深度
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
p_father = []
self.get_stack(p_father,root,p)
q_father = []
self.get_stack(q_father,root,q)
print(p_father)
print(q_father)
# 对两个父节点列表交叉比对
for p in p_father:
for q in q_father:
if p.val==q.val:
return p
return None
def tree_traversal(self,root,node):
# 找到父节点
if root.left==node or root.right==node:
return root
left_node = root.left
if left_node:
self.tree_traversal(left_node,node)
right_node = root.right
if right_node:
self.tree_traversal(right_node,node)
def get_stack(self,stack,root,node):
# 返回node节点的父节点列表
if root == node:
return
parent_node = self.tree_traversal(root,node)
stack.append(parent_node)
self.get_stack(stack,root,parent_node)
解法2:
二叉树左小于右,(假设p为左子节点,q为右子节点)公共父节点满足特性:p.val<=node.val<=q.val
# 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':
root_val = root.val
p_val = p.val
q_val = q.val
if p_val<root_val and q_val<root_val:
return self.lowestCommonAncestor(root.left,p,q)
elif p_val>root_val and q_val>root_val:
return self.lowestCommonAncestor(root.right,p,q)
else:
return root