Python - 递归查找父树
Python - Recursively find parent tree
我有一个二叉树,只有 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 对象。我会递归地查看什么?我无法查看这个 BinaryTree
以下内容应该对您有好处:
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
我有一个二叉树,只有 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 对象。我会递归地查看什么?我无法查看这个 BinaryTree
以下内容应该对您有好处:
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