首页 > 解决方案 > binaryTree 递归循环返回无

问题描述

我调用了这个函数print_tree_array,它应该从左到右打印出一个二叉树数组,如下所示[460, 517, 72, 33, 699, 789, 764, 685, 961, 851]:它做得很好,直到最后一个循环。然后它只返回一个Nonereturn arrayelse声明中所做的事情

我尝试了很多事情并得出结论,二叉树可以正常工作并且“框架”设置正确。

class node:
    def __init__(self, value=None):
        self.value= value
        self.r_child=None
        self.l_child=None

class tree:
    def __init__(self):
        self.root=None

    def insert(self, value, cur_node):
        if(self.root==None):
            self.root=node(value)
        else:
            if(value<cur_node.value):
                if(cur_node.l_child==None):
                    cur_node.l_child=node(value)
                else:
                    self.insert(value, cur_node.l_child)    
            elif(value>cur_node.value):
                if(cur_node.r_child==None):
                    cur_node.r_child=node(value)
                else:   
                    self.insert(value, cur_node.r_child)    

    def print_tree_array(self, cur_node, array=[]):
        if(self.root==None):
            return []
        else:
            if(cur_node!=None):
                self.print_tree_array(cur_node.l_child, array)
                self.print_tree_array(cur_node.r_child, array)
                print(array)
                return array.append(cur_node.value)
            else:
                return array        

    def get_root(self):
        return self.root 


def fill_with_random(tree, size, min_range, max_range):
    from random import randint
    for _ in range(size):
        value = randint(min_range, max_range)
        print(value)
        tree.insert(value, tree.root)
    return tree

current_tree = tree()
current_tree = fill_with_random(tree=current_tree, size=10, min_range=0, max_range=999)
print(current_tree.print_tree_array(cur_node=current_tree.root))
708
999
534
79
692
39
904
979
46
568
[]
[46]
[46, 39]
[46, 39, 79]
[46, 39, 79, 568]
[46, 39, 79, 568, 692]
[46, 39, 79, 568, 692, 534]
[46, 39, 79, 568, 692, 534, 979]
[46, 39, 79, 568, 692, 534, 979, 904]
[46, 39, 79, 568, 692, 534, 979, 904, 999]
None

这就是它打印出来的内容,您可以看到它使用第一行打印的行填充了二叉树。然后它继续漂亮地将树的每个“末端”附加到数组中。但它无法附加最右边的项目并返回整个数组。

标签: pythonbinary-tree

解决方案


array.append 实际上不返回任何东西,但它只附加到原始列表

https://www.programiz.com/python-programming/methods/list/append

如果你愿意,你应该在追加后返回数组。


推荐阅读