簡體   English   中英

如何找到二叉樹中特定節點的深度?

[英]How can I find the depth of a specific node inside a binary tree?

我正在嘗試找出解決此問題的遞歸解決方案。 主要是返回節點所在的二叉樹中的級別。

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

使用此 class 作為值:

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

您需要在find_depth調用中提供有關深度的信息。 它可能看起來像這樣(假設0是通知未找到節點的哨兵):

def find_depth(tree, node, depth=1):
    if node == None:
        return 0

    if tree.value == node:
        return depth

    left_depth = find_depth(tree.left, node, depth+1)
    right_depth = find_depth(tree.right, node, depth+1)
    return max(left_depth, right_depth)

然后你用兩個參數調用它: x = find_depth(tree, 7)

遞歸是一種函數式遺產,因此將其與函數式風格一起使用會產生最佳結果 -

  1. 基本情況:如果輸入tree為空,我們無法搜索,返回None結果
  2. 歸納,輸入tree為空。 如果tree.data與搜索value匹配,則返回當前深度, d
  3. 歸納,輸入tree不為空且tree.data匹配。 返回find.right的遞歸結果或tree.left的遞歸結果
def find (t = None, value = None, d = 1):
  if not t:
    return None              # 1
  elif t.value == value:
    return d                 # 2
  else:
    return find(t.left, value, d + 1) or find(t.right, value, d + 1) # 3

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

t = tree \
  ( 3
  , tree(7, tree(9), tree(3))
  , tree(1)
  )

print(find(t, 7)) # 2
print(find(t, 99)) # None

您也可以在tree class 中實現find方法

def find (t = None, value = None, d = 1):
  # ...

class tree
  def __init__ #...

  def find(self, value)
    return find(self, value)

print(t.find(7)) # 2
print(t.find(99)) # None

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM