递归与二叉树_leetcode236

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None


# 二叉树的公共祖先是什么?
# 若p、q在根节点的两边 则根是最近的公共祖先
# #若p、q在同一边,则 要么p 要么q


# 函数的定义: 返回p、q的最近公共祖先
# 20190305 找工作期间
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""

# 根节点为 p、q
if root.val == p.val or root.val == q.val:
return root
# p、q都在左子树
if self.findNode(root.left,p.val) and self.findNode(root.left,q.val):
return self.lowestCommonAncestor(root.left,p,q)
# p、q都在右子树
if self.findNode(root.right,p.val) and self.findNode(root.right,q.val):
return self.lowestCommonAncestor(root.right,p,q)
# p、q 在左右两侧
return root

def findNode(self,root ,key):

if not root:
return False

if root.val == key:
return True

return self.findNode(root.left,key) or self.findNode(root.right,key)



class Solution2(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""

if not root or root.val == p.val or root.val == q.val:
return root


left = self.lowestCommonAncestor(root.left,p,q)
right = self.lowestCommonAncestor(root.right,p,q)


if (left and right):
return root

if not left:
return right
if not right:
return left

return root



class Solution3(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""


if not root :
return root
if p == root or q == root:
return root
pathP = [root]
pathQ = [root]
self.findPath(root,p,pathP)
self.findPath(root,q,pathQ)

i = 0
while i < len(pathP) and i < len(pathQ) and pathQ[i] == pathP[i]:
ans = pathP[i]
i += 1
return ans

def findPath(self,root,node,path):


if root.val == node.val:
return True

if root.left:

path.append(root.left)

if self.findPath(root.left,node,path):
return True
else:
path.pop()

if root.right:
path.append(root.right)

if self.findPath(root.right,node,path):
return True
path.pop()
return False


# class Solution4(object):
# def lowestCommonAncestor(self, root, p, q):
# """
# :type root: TreeNode
# :type p: TreeNode
# :type q: TreeNode
# :rtype: TreeNode
# """
# pass
#
# if not root:
# return root
# if p == root or q == root:
# return root
# pathP = []
# pathQ = []
# self.findPath(root, p, pathP)
# self.findPath(root, q, pathQ)
#
# i = 0
# while i < len(pathP) and i < len(pathQ) and pathQ[i] == pathP[i]:
# ans = pathP[i]
# i += 1
# return ans
#
# def findPath(self, root, node, path):
#
# if not root:
# return## if root.val == node.val:# path.append(root)# return## if root.left:# path.append(root)# self.findPath(root.left, node, path)## if root.right:# path.pop()# self.findPath(root.right, node, path)
posted @ 2019-03-17 14:08  AceKo  阅读(181)  评论(0编辑  收藏  举报