题解 | #在二叉树中找到两个节点的最近公共祖先#
在二叉树中找到两个节点的最近公共祖先
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 dsf(self,root,o1,o2):
if root is None:
return root
if root.val == o1 or root.val == o2:
return root
left = self.dsf(root.left, o1, o2)
right = self.dsf(root.right, o1, o2)
if left is None and right is None:
return None
if left is None: return right
if right is None: return left
return root
def lowestCommonAncestor(self , root , o1 , o2 ):
# write code here
node = self.dsf(root, o1,o2)
return node.val