[英]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)
。
遞歸是一種函數式遺產,因此將其與函數式風格一起使用會產生最佳結果 -
tree
為空,我們無法搜索,返回None
結果tree
不為空。 如果tree.data
與搜索value
匹配,則返回當前深度, d
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.