【问题标题】:Binary tree from nested dictionary in PythonPython中嵌套字典的二叉树
【发布时间】: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


【解决方案1】:

遍历字典的递归函数应该可以很好地完成这项工作:

def VertexFromDict(d):
    if not d: return None
    v       = Vertex()
    v.value = d['value']
    v.left  = VertexFromDict(d.get('left'))
    v.right = VertexFromDict(d.get('right'))
    return v

输出:

root = VertexFromDict(t)
printBTree(root,lambda v:(str(v.value),v.left,v.right))

      1
   __/ \_
  2      2
 / \    / \
3   4  4   3

注意:我用来打印树的printBTree函数可以在here找到。

【讨论】:

    【解决方案2】:

    你应该让你的 Vertex 构造函数更加通用,以便它可以使用参数来初始化属性。

    像这样:

    class Vertex:
        def __init__(self, value, left=None, right=None):
            self.value = value
            self.left = left
            self.right = right
    

    那么你的函数就可以递归了,像这样:

    def dict_to_binary_tree(data):
        return data and Vertex(
                data["value"], 
                dict_to_binary_tree(data["left"]), 
                dict_to_binary_tree(data["right"])
            )
    

    要进行简单的深度优先迭代,请在 Node 类上定义 __iter__

    class Vertex:
        def __init__(self, value, left=None, right=None):
            self.value = value
            self.left = left
            self.right = right
    
        def __iter__(self):
            yield self.value
            if self.left:
                yield from self.left
            if self.right:
                yield from self.right
    

    现在你的主代码可以做到这一点:

    root = dict_to_binary_tree(t)
    print(*root)  # will print values in depth-first, pre-order
    

    【讨论】:

      猜你喜欢
      • 2013-04-18
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多