代码拉取完成,页面将自动刷新
class Node(object):
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
def __repr__(self):
return str(self.key)
class BinaryTree(object):
def lca(self, root, node1, node2):
if None in (root, node1, node2):
return None
if (not self._node_in_tree(root, node1) or
not self._node_in_tree(root, node2)):
return None
return self._lca(root, node1, node2)
def _node_in_tree(self, root, node):
if root is None:
return False
if root is node:
return True
left = self._node_in_tree(root.left, node)
right = self._node_in_tree(root.right, node)
return left or right
def _lca(self, root, node1, node2):
if root is None:
return None
if root is node1 or root is node2:
return root
left_node = self._lca(root.left, node1, node2)
right_node = self._lca(root.right, node1, node2)
if left_node is not None and right_node is not None:
return root
else:
return left_node if left_node is not None else right_node
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。