简体   繁体   English

递归获取二叉树中节点的路径

[英]Recursively obtaining path to node in binary tree

I am having issues getting the path to a node in a binary tree. 我在获取二叉树中节点的路径时遇到问题。 Specifically, I don't know how to pop elements off of the stack as I return from a stack frame. 具体来说,当我从堆栈框架返回时,我不知道如何从堆栈中弹出元素。

def getPath(self, target):

    stack = []

    def _getPath(head):
        nonlocal stack
        nonlocal target

        stack.append(head)

        if head.value == target:
            return stack
        if head.left is not None:
            _getPath(head.left)
        if head.right is not None:
            _getPath(head.right)

    _getPath(self.root)

    return stack

Currently, the stack will contain all of the elements in the tree. 当前,堆栈将包含树中的所有元素。

A problem here is: the information of when the target is found has to be propagated back to the called instances of getPath . 这里的问题是:关于何时找到目标的信息必须传播回getPath的调用实例。 The construction of the stack is kind of a "side effect" of the finding. 堆叠的构造是该发现的“副作用”。 Therefore I propose you return a boolean value in getPath , that is True iff the target was found within the subtree currently investigated. 因此,我建议您在getPath返回一个布尔值,如果在当前调查的子树中找到目标,则返回True。 Then we know we have to attach a value to the "stack": 然后,我们知道必须将一个值附加到“堆栈”:

def getPath(self, target):

    stack = []

    def _getPath(head):
        nonlocal stack
        nonlocal target
        if head.value == target:
            stack.append(head)
            return True
        for child in (head.left, head.right):
            if child is not None:
                if  _getPath(child):
                    stack.append(head)
                    return True
        return False


    _getPath(self.root)
    return reversed(stack)

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

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