简体   繁体   English

生成、遍历和打印二叉树

[英]Generating, traversing and printing binary tree

I generated perfectly balanced binary tree and I want to print it.我生成了完美平衡的二叉树,我想打印它。 In the output there are only 0s instead of the data I generated.在输出中只有 0 而不是我生成的数据。 I think it's because of the line in function printtree that says print(tree.elem) , cause in the class self.elem = 0 .我认为这是因为函数printtree中的一行表示print(tree.elem) ,导致类self.elem = 0

How can I connect these two functions generate and printtree ?如何连接这两个函数generateprinttree

class BinTree:

    def __init__(self):
        self.elem = 0
        self.left = None
        self.right = None


def generate(pbt, N):
    if N == 0:
        pbt = None
    else:
        pbt = BinTree()
        x = input()
        pbt.elem = int(x)
        generate(pbt.left, N // 2)
        generate(pbt.right, N - N // 2 - 1)

def printtree(tree, h):
    if tree is not None:
        tree = BinTree()
        printtree(tree.right, h+1)
        for i in range(1, h):
            print(end = "......")
            print(tree.elem)
            printtree(tree.left, h+1)

Hope somebody can help me.希望有人可以帮助我。 I am a beginner in coding.我是编码初学者。

For example: N=6, pbt=pbt, tree=pbt, h=0例如:N=6, pbt=pbt, tree=pbt, h=0

input:输入:

1
2
3
4
5
6

and the output:和输出:

......5 
............6 
1 
............4 
......2 
............3

I'd suggest reading up on: https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/我建议阅读: https : //www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/

Basically, there are three ways to traverse a binary tree;基本上,有三种方法可以遍历二叉树; in-order, post-order and pre-order.按订单、后订单和预订单。

The issue with your print statement is that, you're reassigning the tree that is being passed in, to an empty tree.您的打印语句的问题在于,您正在将传入的树重新分配给一棵空树。

  if tree is not None:
        tree = BinTree()

Right?对? If tree is not none and has something, lets reassign that to an empty tree.如果 tree 不是 none 并且有东西,让我们将它重新分配给一个空树。

Traversing a tree is actually a lot more simpler than you'd imagine.遍历一棵树实际上比你想象的要简单得多。 I think the complexity comes in just trying to imagine in your head how it all works out, but the truth is that traversing a tree can be done in 3 - 4 lines.我认为复杂性来自只是试图在你的脑海中想象这一切是如何运作的,但事实是遍历一棵树可以在 3 - 4 行中完成。

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

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