python - 如何找到二叉树中特定节点的深度?

标签 python recursion binary-tree

我正在尝试找出这个问题的递归解决方案。主要是返回该节点在二叉树中的级别。

def find_depth(tree, node):
    if node == None:
        return 0 
    else: 
        return max(find_depth(tree.left))
        #recursive solution here 

使用此类作为值:

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

示例:调用 find_depth(tree, 7) 应返回树中 7 所在的级别。 (2级)

   3
  / \
  7  1  <------ return that 7 is at level 2
 / \  
 9 3   

最佳答案

也许这就是您正在寻找的

    def find_depth(tree, node):
        if node is None or tree is None:
            return 0

        if tree == node:
            return 1

        left = find_depth(tree.left, node)
        if left != 0:
            return 1 + left
        right = find_depth(tree.right, node)
        if right != 0:
            return 1 + right

        return 0

关于python - 如何找到二叉树中特定节点的深度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61944860/

相关文章:

PHP数组,使用 'depth'的键将数组项的深度递归地添加到数组中

C 错误 : dereferencing pointer to incomplete type

python - 空集的真值

python - 将字符串传递给函数时出现问题

python - 如何将嵌套的数字列表转换为字符串列表?

c++ - 维护堆属性

java - 如何在java二叉树中实现通用的中序遍历?

python - django - 捕获多个异常

algorithm - 递归、记忆化和动态规划之间有什么区别?

使用应用函数重写循环