一.题目:
求二叉树中两个节点的最近公共祖先.
二.解题思路:
首先,很通俗的解法就是找到两个节点的路径,然后对两条路径进行判断,分叉口的上一个节点就是这两个节点的最近公共祖先.
代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
#常规解法
p_result = []
q_result = []
def getPath1(root,node,path,result):
if root == None:
return False
path.append(root)
if root == node:
result.append(path[:])
if root.left:
getPath1(root.left,node,path,result)
if root.right:
getPath1(root.right,node,path,result)
path.pop()
def getLastCommonNode(path1,path2):
pLast=None
i=0
while i<min(len(path1),len(path2)):
if path1[i]==path2[i]:
pLast=path1[i]
i+=1
else:
break
return pLast
if not root or not p or not q:
return None
getPath1(root,p,[],p_result)
getPath1(root,q,[],q_result)
p_result = p_result[0]
q_result = q_result[0]
return getLastCommonNode(p_result,q_result)
此外还有一种递归方法,想不到啊=-=
直接贴代码
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if not root:
return None
if root in (p,q):
return root
left = self.lowestCommonAncestor(root.left,p,q)
right = self.lowestCommonAncestor(root.right,p,q)
return root if left and right else left or right