简体   繁体   English

使用 dfs 遍历二叉树,在给定点停止(在 Python 中)

[英]Traverse a binary tree using dfs, stopping at a given point (in Python)

I'm learning about some basic computer science concepts.我正在学习一些基本的计算机科学概念。 As a demo, I'm creating a script in Python that will perform various functions on a binary tree.作为演示,我正在用 Python 创建一个脚本,该脚本将在二叉树上执行各种功能。 I've been able to successfully program most of these functions, except for one specific one.除了一个特定的功能外,我已经能够成功地对大多数这些功能进行编程。

For a binary tree created from an array of integers, I would like to do a depth first search for an integer, and return the path that was taken through the tree up until that integer was found as an array (with the last number in that array being the number that was being searched for).对于从整数数组创建的二叉树,我想对整数进行深度优先搜索,并返回通过树的路径,直到找到该整数作为数组(其中的最后一个数字)数组是正在搜索的数字)。 As soon as the first match for that integer is found, I want to stop traversing the tree.一旦找到该整数的第一个匹配项,我就想停止遍历树。

For example, for an inorder dfs of array [3,2,4,1,4,6,8,5] for integer 4, it should return [1,2,3,4]例如,对于整数 4 的数组 [3,2,4,1,4,6,8,5] 的中序 dfs,它应该返回 [1,2,3,4]

For integer 5 it should return [1,2,3,4,4,5] etc.对于整数 5,它应该返回 [1,2,3,4,4,5] 等。

Here is my code:这是我的代码:

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

    def getValue(self):
        return self.value

def buildTree(array):
    print("building tree....")
    root=Node(array[0])
    del(array[0])
    for a in array:
        insert(root,Node(a))
    print("building complete")
    return root

def insert(root,node): 
    if root is None: 
        root = node 
    else: 
        if root.value < node.value: 
            if root.right is None: 
                root.right = node 
            else: 
                insert(root.right, node) 
        else: 
            if root.left is None: 
                root.left = node 
            else: 
                insert(root.left, node) 

def depthFirstSearch(root,target,results,subSearch):
#0:preorder
#1:inorder
#2:postorder
    if root!=None:

        if subSearch==0:
            results.append(root.getValue())
            if root.getValue()==target:
                return results

        depthFirstSearch(root.left,target,results,subSearch)

        if subSearch==1:
            results.append(root.getValue())
            if root.getValue()==target:
                return results

        depthFirstSearch(root.right,target,results,subSearch)

        if subSearch==2:
            results.append(root.getValue())
            if root.getValue()==target:
                return results

    return results

if __name__ == '__main__':
    #stuff that gets our arguments
    #...
    array=[3,2,4,1,4,6,8,5] #we would actually get this as an argument, but using this for example array
    target=4 #example target
    subSearch=1 #using inorder traversal for this example

    root=buildTree(array)
    results=[]
    results=depthFirstSearch(root,target,results,subSearch) 
    print(results) #expected:[1,2,3,4]

Okay this is easy, just use an Additional variable flag and then your function becomes好的,这很简单,只需使用附加变量标志,然后您的函数就变为

def depthFirstSearch(root,target,results,subSearch, flag = 0):
#0:preorder
#1:inorder
#2:postorder
    if root!=None:

        if subSearch==0:
            results.append(root.getValue())
            if root.getValue()==target:
                return results, 1

        results, flag =depthFirstSearch(root.left,target,results,subSearch)
        if flag == 1:
            return results, flag
        if subSearch==1:
            results.append(root.getValue())
            if root.getValue()==target:
                return results, 1

        results, flag = depthFirstSearch(root.right,target,results,subSearch)
        if flag == 1:
            return results, flag

        if subSearch==2:
            results.append(root.getValue())
            if root.getValue()==target:
                return results, 1

    return results, flag

Here Flag changes to one and that is propagated as the function stack shrinks, keeping them after each recursive calls takes care of this.此处 Flag 更改为 1,并随着函数堆栈的缩小而传播,在每次递归调用后保留它们会处理此问题。

Also in main function, the function call becomes同样在主函数中,函数调用变为

results, _=depthFirstSearch(root,target,results,subSearch)

Since flag = 0 is present in function definition you just need to discard the second variable, you can even use that to check if the element was found in the tree rather than just printing the whole tree if element is not present.由于函数定义中存在flag = 0 ,您只需要丢弃第二个变量,您甚至可以使用它来检查元素是否在树中找到,而不是仅在元素不存在时打印整个树。

If you have any doubts or concerns, comment below.如果您有任何疑问或疑虑,请在下方评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM