【发布时间】:2021-11-19 01:52:50
【问题描述】:
如何在给定嵌套字典的情况下构建二叉树?理想情况下,我希望访问根,然后以常规的深度优先或广度优先方式遍历树。
在从嵌套字典构建树的时间或空间方面,我并不十分关心效率,因此我不介意在此过程中使用额外的数据结构。我的主要关注点是一个全面而直观的解决方案。我现在不知道从哪里开始,所以非常感谢任何帮助。
class Vertex:
"""Vertex object in a binary tree."""
def __init__(self):
"""Initialize Vertex object.
Fields
----------
value : int
The value of node v
left : None
The left child of node v
right : None
The right child of node v
"""
self.value = None
self.left = None
self.right = None
def dict_to_binary_tree(data):
"""Implementation here."""
return root
if __name__ == '__main__':
t = {
"value": 1,
"left": {
"value": 2,
"left": {
"value": 3,
"left": None,
"right": None
},
"right": {
"value": 4,
"left": None,
"right": None
}
},
"right": {
"value": 2,
"left": {
"value": 4,
"left": None,
"right": None
},
"right": {
"value": 3,
"left": None,
"right": None
}
}
}
root = dict_to_binary_tree(t)
# traverse tree i.e. dfs(root), bfs(root)
这是二叉树的样子:
1
/ \
2 2
/ \ / \
3 4 4 3
【问题讨论】:
-
您在尝试编写此代码时究竟遇到了什么问题?正如目前所呈现的那样,您的问题看起来像“为我编写代码”。请阅读meta.stackoverflow.com/questions/334822/…
-
我觉得你的
Vertex.__init__方法应该有一定的三个参数。 -
你的问题没有问题。请参阅How to Ask 以及如何创建minimal reproducible example。
-
编辑:我已经在帖子中明确提出了这个问题,谢谢你的帮助。
标签: python dictionary data-structures tree binary-tree