题解 | #在二叉树中找到两个节点的最近公共祖先#
在二叉树中找到两个节点的最近公共祖先
http://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# @param root TreeNode类
# @param o1 int整型
# @param o2 int整型
# @return int整型
#
class Solution:
def lowestCommonAncestor(self , root , o1 , o2 ):
# write code here
def lowestRec(root,o1,o2):
if root is None or root.val == o1 or root.val == o2:
return root
left = lowestRec(root.left, o1, o2)
right = lowestRec(root.right, o1, o2)
if left is None:
return right
if right is None:
return left
return root
return lowestRec(root, o1, o2).val
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# @param root TreeNode类
# @param o1 int整型
# @param o2 int整型
# @return int整型
#
class Solution:
def lowestCommonAncestor(self , root , o1 , o2 ):
# write code here
def lowestRec(root,o1,o2):
if root is None or root.val == o1 or root.val == o2:
return root
left = lowestRec(root.left, o1, o2)
right = lowestRec(root.right, o1, o2)
if left is None:
return right
if right is None:
return left
return root
return lowestRec(root, o1, o2).val

阿里云成长空间 743人发布