二叉树的深度

时间:2015-04-17 08:47:17

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

我用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)

1 个答案:

答案 0 :(得分:0)

我将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