题目:
给出一个二叉树,输入两个树节点,求它们的最低公共祖先。
一个树节点的祖先节点包括它本身。
注意:
输入的二叉树不为空;
输入的两个节点一定不为空,且是二叉树中的节点;
解答:
解法一,使用递归,若两个树节点在根节点的左右子树上,则公共节点为根节点;若两个树节点都在某一子树上,则公共节点在该子树上。这个方法递归都要查询某一子树上是否有节点存在,时间复杂度较高。
# 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
"""
if root == q or root == p:
return root
if not root.left:
return self.lowestCommonAncestor(root.right, p, q)
if not root.right:
return self.lowestCommonAncestor(root.left, p, q)
pInLeftTree, qInLeftTree = self.isNodeInTree(root.left, p), self.isNodeInTree(root.left, q)
if pInLeftTree and qInLeftTree:
return self.lowestCommonAncestor(root.left, p, q)
if not pInLeftTree and not qInLeftTree:
return self.lowestCommonAncestor(root.right, p, q)
return root
def isNodeInTree(self, root, node):
if root == node:
return True
return (root.left and self.isNodeInTree(root.left, node)) or (root.right and self.isNodeInTree(root.right, node))
解法二,先找出从根节点到两个树节点的路径,然后转化为求两个链表的公共节点。
# 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
"""
pathToP, pathToQ = [], []
self.iterate(root, p, pathToP)
self.iterate(root, q, pathToQ)
diff = len(pathToP) - len(pathToQ)
if diff < 0:
startQ = len(pathToQ) -1 + diff
startP = len(pathToP) - 1
else:
startP = len(pathToP) -1 - diff
startQ = len(pathToQ) - 1
while(startP >= 0):
if pathToP[startP] == pathToQ[startQ]:
return pathToP[startP]
else:
startP -= 1
startQ -= 1
def iterate(self, root, node, path):
path.append(root)
if root == node:
return True
if root.left:
if self.iterate(root.left, node, path):
return True
if root.right:
if self.iterate(root.right, node, path):
return True
path.pop()