简体   繁体   English

在Python类中附加栈(自己)

[英]Append (self) with stacks in Python classes

I am doing/learning data structures and algorithms and I came across the following code: 我在做/学习数据结构和算法,遇到了以下代码:

class BinaryTree:

    def __init__(self, root_data):
        self.data = root_data
        self.left_child = None
        self.right_child = None

    def inorder_iterative(self):
        inorder_list = []
        return inorder_list

    def get_right_child(self):
        return self.right_child

    def get_left_child(self):
        return self.left_child

    def set_root_val(self, obj):
        self.data = obj

    def get_root_val(self):
        return self.data

    def preorder_iterative(self):
        pre_ordered_list = [] #use this as result
        stack = []
        stack.append(self)

        while len(stack)>0:
            node = stack.pop() #should return a value 
            pre_ordered_list.append(node.get_root_val())
            if node.right_child:
                stack.append(node.get_right_child())
            if node.left_child:
                stack.append(node.get_left_child())
        return pre_ordered_list


    bn = BinaryTree(1)
    bn.left_child = BinaryTree(2)
    bn.right_child = BinaryTree(3)
    print (bn.preorder_iterative())

I am very lost about stack.append(self) part. 我对stack.append(self)部分非常迷失。 I am not sure what is the point of having this line and I don't fully understand the concept of .append(self) . 我不确定拥有这条线的目的是什么,我也不完全理解.append(self)的概念。 I have learnt that self represents the instance of the class. 我了解到, self代表了课堂的实例。

The purpose of the stack is to simulate recursion. 堆栈的目的是模拟递归。

The initial value placed on the stack is the tree itself (in the form of its root node). 放在堆栈上的初始值是树本身(以其根节点的形式)。 Its value is retrieved, and then each subtree is placed on the stack. 检索其值,然后将每个子树放在堆栈上。 On the next iteration of the loop, the left child is removed, processed, and replaced with its children, if any. 在循环的下一次迭代中,左子级将被删除,处理并替换为其子级(如果有)。 The loop continues as long as there is anything on the stack to process. 只要堆栈上有任何要处理的内容,循环就会继续。 Once everything on the left side of the tree as been processed, you'll finally start on the right child (placed the stack way at the beginning of the loop). 处理完树左侧的所有内容之后,您最终将从正确的子级开始(将堆栈放置在循环的开头)。

Compare to a recursive version: 与递归版本比较:

def preorder_recursive(self):
    result = [self.get_root_val()]
    if node.left_child:
        result.extend(node.left_child.preorder_recursive())
    if node.right_child:
        result.extend(node.right_child.preorder_recursive())
    return result

Each recursive call essentially puts self on a stack, allowing the left child (and its descendants) to be processed before eventually returning to the root and moving to its right child. 每个递归调用本质上都会将self放在堆栈上,从而允许在最终返回到根并移至其右子之前处理左子(及其子代)。

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

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