1 Star 0 Fork 0

蓝桥云课/python-100

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
035-tree_lca.py 1.19 KB
一键复制 编辑 原始数据 按行查看 历史
xiaoyi733112 提交于 2020-02-20 17:17 . python-100 answer
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
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/lanqiao-courses/python-100.git
git@gitee.com:lanqiao-courses/python-100.git
lanqiao-courses
python-100
python-100
master

搜索帮助