我有一个二叉树,只有self._root和self._nodes。无论如何我可以弄清楚如何通过构造函数找到当前树的父树?
class BinaryTree:
"""
- If _root is None, then _nodes is empty and _parent_tree is None
- nodes is allowed to contain empty nodes
- if _parent_tree is not empty, then self is in _parent_tree._nodes
"""
def __init__(self, root, nodes):
"""Initialize a new BinaryTree.
@type self: BinaryTree
@type root: object
@type nodes: list[BinaryTree]
@rtype: None
"""
self._root = root
self._nodes = nodes
self._parent_tree = None
"""Implement _parent_tree"""
if self._root is not None:
"""implement"""
else:
pass
说实话,我不知道如何开始这个。如何在不构造此对象的情况下知道任何其他BinaryTree对象。我会以递归方式查看什么?我不太可能透过这个BinaryTree
答案 0 :(得分:1)
以下应该对你有用:
class BinaryTree:
def __init__(self, root, nodes):
self._root = root
self._nodes = nodes
self._parent_tree = None
if self._root is not None:
for node in self._nodes:
if node is not None:
node._parent_tree = self
else:
pass