给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
示例 1:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
- 题解
# 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(not root or root==p or root==q):
return root
left=self.lowestCommonAncestor(root.left,p,q)
right=self.lowestCommonAncestor(root.right,p,q)
if(left is None):return right
if(right is None):return left
if( right and left):return root
##找路径
####回溯
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def helper(res,root,target,currPath):
if(not root):
return
if(root==target):
currPath.append(root)
res.extend(currPath[:])
return
currPath.append(root)
helper(res,root.left,target,currPath)
helper(res,root.right,target,currPath)
currPath.pop()
resp=[]
resq=[]
helper(resp,root,p,[])
helper(resq,root,q,[])
if(len(resp)<len(resq)):
resp,resq=resq,resp
for i in range(len(resq)):
if(resp[i]!=resq[i] and i>0):
return resp[i-1]
return resq[-1]
###哈希法
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
hashmap={}
def helper(root):
if(not root):
return
if(root.left):hashmap[root.left]=root
if(root.right):hashmap[root.right]=root
helper(root.left)
helper(root.right)
helper(root)
l1=p
l2=q
while(l1!=l2):
l1=hashmap.get(l1,q)
l2=hashmap.get(l2,p)
return l1