【问题标题】:Depth of binary tree二叉树的深度
【发布时间】:2015-04-17 21:54:32
【问题描述】:

我用 Node 创建了一个类:

class Node:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

并用一些数据填充树,我想要没有递归的树的深度:

def depth(self, data):
    self.depth = dict()
    root = self.dict[self.root] # this works, I got the root, it is declared in another init
    if root.data == data:
        return 0
    q = set()
    q.add(0)
    q.add(root)
    while q:
        element = q.pop()
        if type(element) == int: 
            if q == set():      
                break
            else:
                key = element
                q.add(element+1)
        else:
            v = element
            try:
                self.depth[v.data].add(key)
            except KeyError:
                self.depth[v.data] = key
            if v.right is not None:
                q.add(v.right)
            if v.left is not None:
                q.add(v.left)
            if data == v.data:
               break
    return self.depth[data]

此代码应返回元素数据的深度。它适用于列表,但我对它们有超时,所以我必须使用 set 代替。使用集合会得到错误的结果。 (例如 19 而不是 6)

【问题讨论】:

  • 为什么不想用递归来求树的深度?
  • 代码经过大量节点测试,达到最大递归。
  • 你能解释一下q的含义吗?你在里面放了不同类型的东西,即数字和Nodes。
  • 如果你不打算使用递归,那么就使用堆栈。
  • 0 表示整数深度,如果元素类型为 int 则为 +1,如果类型为 Node than,则加载左、右并将深度保存到 dict 中。

标签: python python-3.x binary-tree


【解决方案1】:

我将this answer 翻译成 Python:

def maxdepth(r):
    depth = 0
    wq = []
    path = []
    wq.append(r)
    while wq:
        r = wq[-1]
        if path and r == path[-1]:
            if len(path) > depth:
                depth = len(path)
            path.pop()
            wq.pop()
        else:
            path.append(r)
            if r.right is not None:
                wq.append(r.right)
            if r.left is not None:
                wq.append(r.left)
    return depth

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 2012-10-12
    • 2014-08-07
    • 2022-06-26
    相关资源
    最近更新 更多