Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用python实现二叉树_Python_Binary Tree - Fatal编程技术网

用python实现二叉树

用python实现二叉树,python,binary-tree,Python,Binary Tree,我想创建一个二叉树,但最终结果仍然是错误的 二叉树的预期输出为: 15 25 20 30 10 7 13 14 6 9 11 17 27 32 23 root node : 6 但我的程序电流输出如下: 6 7 9 10 11 13 14 15 17 20 23 25 27 30 32 我的大问题是将值插入节点的逻辑性 这是我的节目: class Tree: val = None left = None right = None def __init__(s

我想创建一个二叉树,但最终结果仍然是错误的

二叉树的预期输出为:

15 25 20 30 10 7 13 14 6 9 11 17 27 32 23
root node : 6
但我的程序电流输出如下:

6 7 9 10 11 13 14 15 17 20 23 25 27 30 32 
我的大问题是将值插入节点的逻辑性

这是我的节目:

class Tree:
    val = None
    left = None
    right = None
    def __init__(self, val):
        self.val = val
    def insert(self, val):
        if self.val is not None:
            if val < self.val:
                if self.left is not None:
                    self.left.insert(val)
                else:
                    self.left = Tree(val)
            elif val > self.val:
                if self.right is not None:
                    self.right.insert(val)
                else:
                    self.right = Tree(val)
            else:
                return
        else:
            self.val = val
            print("new node added")

    def showTree(self):
        if self.left is not None:
            self.left.showTree()
        print(self.val, end = ' ')
        if self.right is not None:
            self.right.showTree()
root= Tree(6)

root.insert(15)
root.insert(25)
root.insert(20)
root.insert(30)
root.insert(10)
root.insert(7)
root.insert(13)
root.insert(14)

root.insert(9)
root.insert(11)
root.insert(17)
root.insert(27)
root.insert(32)
root.insert(23)

root.showTree()
类树:
val=无
左=无
右=无
定义初始值(self,val):
self.val=val
def插入(自身,val):
如果self.val不是None:
如果valself.val:
如果self.right不是None:
self.right.insert(val)
其他:
self.right=树(val)
其他:
返回
其他:
self.val=val
打印(“添加新节点”)
def showTree(自我):
如果self.left不是无:
self.left.showTree()
打印(self.val,end='')
如果self.right不是None:
self.right.showTree()
根=树(6)
根.插入(15)
根.插入(25)
根.插入(20)
根.插入(30)
根.插入(10)
根.插入(7)
根.插入(13)
根.插入(14)
根.插入(9)
根.插入(11)
根.插入(17)
根.插入(27)
root.insert(32)
根.插入(23)
root.showTree()

我仍然很难得到正确的结果。我需要你的意见来解决这个问题。

你的“预期输出”实际上是输入顺序(根除外)。这真的是您必须得到的输出吗?乍一看:对于您想要的树类型(平衡;父级总是小于子级),您需要在新值较低时替换当前值,并递归地将当前值传播给子级。如何?我应该从哪里开始@L3viathanyes是的,结果输出应该是@trincott,那么输出的逻辑是什么?一般规则是什么?缺少对此挑战的一些描述。。。