简体   繁体   English

按顺序打印二叉树python

[英]Print a binary tree, python, in inorder

Me and my friend are doing some school work with programming in Python 3.1 and are VERY stuck. 我和我的朋友正在用Python 3.1进行一些功课,非常困。 We're programming a binary tree and it's working fine except when we want to print all the nodes in inorder in a way that would create a sentence (all the words in inorder just after one another in a row). 我们正在编程一个二叉树,它的工作正常,除了当我们想要以一种能够创建句子的方式(所有单词按顺序依次排列)顺序打印所有节点时。 We have been looking all over the internet for clues as to how to procede and we've been working with this little thing for like two hours. 我们一直在互联网上寻找有关如何进行的线索,并且我们已经花了两个小时研究这个小东西。 Any advice/help would be awesome. 任何建议/帮助都会很棒。

Our program/Binary tree: 我们的程序/二叉树:

class Treenode:  
    def __init__(self, it = None, le = None, ri = None):  
        self.item = it  
        self.left = le  
        self.right = ri  

class Bintree:  
    def __init__(self):  
        self.item = None  
        self.left = None  
        self.right = None  

    def put(self, it = None):
        key = Treenode(it)
        if self.item == None:
            self.item = key
            return
        p = self.item
        while True:
            if key.item < p.item:
                if p.left == None:
                    p.left = key
                    return
                else:
                    p = p.left
            elif key.item > p.item:
                if p.right == None:
                    p.right = key
                    return
                else:
                    p = p.right
            else:
                return

    def exists(self, it):
        key = it
        p = self.item
        if p == key:
            return True
        while True:
            if key < p.item:
                if p.left == None:
                    return False
                else:
                    p = p.left
            elif key > p.item:
                if p.right == None:
                    return False
                else:
                    p = p.right
            else:
                return

    def isEmpty(self):
        if self.item == None:
            return True
        else:
            return False

def printtree (Treenode):
    if Treenode.left != None:
        printtree (Treenode.left)
    print (Treenode.item)
    if Treenode.right != None:
        printtree (Treenode.right)

We get a sort of print when we run the program which looks like this: "bintree.Treenode object at 0x02774CB0", which is not what we want. 运行程序时,我们得到一种打印结果:“ bintree.Treenode对象位于0x02774CB0”,这不是我们想要的。

We use the tree by running this: 我们通过运行以下命令来使用树:

import bintree

tree = bintree.Bintree()
print(tree.isEmpty())    # should give True
tree.put("solen")
print(tree.isEmpty())    # should give False
tree.put("gott")
tree.put("sin")
tree.put("hela")
tree.put("ban")
tree.put("upp")
tree.put("himlarunden")
tree.put("manen")
tree.put("seglar")
tree.put("som")
tree.put("en")
tree.put("svan")
tree.put("uti")
tree.put("midnattsstuden")

print(tree.exists("visa"))     # should give False
print(tree.exists("ban"))      # should give True
tree.printtree()               # print sorted

Also, the second last row gives us "None" instead of "True", which is wierd. 另外,倒数第二行给出的结果是“ None”,而不是“ True”,这很奇怪。

print(tree.exists("visa")) returns None , because in the last line of exists() there's return statement without any value (which defaults to None ). print(tree.exists("visa"))将返回None ,因为在最后一行exists()return声明没有任何值(默认为None )。

Also you shouldn't name a printtree argument Treenode since it's a name of an existing class and that might lead to confusion. 另外,您不应该为printtree参数Treenode命名,因为它是现有类的名称,并且可能导致混淆。 It should look more like: 它看起来应该更像:

def printtree(tree_node):
    if tree_node.left is not None:
        printtree(tree_node.left)
    print(tree_node.item)
    if tree_node.right is not None:
        printtree(tree_node.right)

Another thing is calling printtree - it's a function, not Bintree method, so I suppose you should call it printtree(tree) . 另一件事是调用printtree它是一个函数,而不是Bintree方法,因此我想应该将其printtree(tree)

One way to make testing easier is to use -assert()- instead of printing things and then referring back to your code. 使测试更容易的一种方法是使用-assert()-而不是打印内容,然后再引用您的代码。

tree = Bintree()
assert(tree.isEmpty())
tree.put("solen")
assert(not tree.isEmpty())
tree.put("gott")
tree.put("sin")
tree.put("hela")
tree.put("ban")

http://docs.python.org/reference/simple_stmts.html#the-assert-statement http://docs.python.org/reference/simple_stmts.html#the-assert-statement

It raises an error if its condition is not true. 如果条件不成立,则会引发错误。 I know that doesn't fix your bug but making things less ambiguous always helps debugging. 我知道这并不能解决您的错误,但是使事情变得不太模糊总是可以帮助调试。

To print a binary tree, if you are printing a leaf you just print the value; 要打印二叉树,如果要打印叶子,则只需打印值即可; otherwise, you print the left child then the right child. 否则,先打印左边的孩子,然后再打印右边的孩子。

def print_tree(tree):
    if tree:
        print tree.value
        print_tree(tree.left)
        print_tree(tree.right)

You are not specifying a starting case for printtree(). 您没有为printtree()指定起始条件。 You're defining how to recurse through your tree correctly, but your call to printtree() has no node to start at. 您正在定义如何正确地遍历树,但是对printtree()的调用没有任何起点。 Try setting a default check to see if a parameter is passed in, and if one isn't start at the head node of the bintree. 尝试设置默认检查以查看是否传入了一个参数,以及是否不是从二叉树的头节点开始的。

The reason your second to last line is printing None is because, in your exists method, you just have a "return", rather than a "return True", for the case of finding a `p.item' that is equal to key. 倒数第二行打印None的原因是,在存在的方法中,对于查找等于key的“ p.item”,您只有一个“ return”,而不是“ return True”。 。

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

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