简体   繁体   English

二叉树遍历python

[英]Binary Seacrh tree Traversing python

def traverse(self):
    if self.root !=None:
        print('*****Traversing*****')
        print('self.root is', self.root.data)
        print('self.root.Left is', self.root.leftchild.data)
        print('self.root.Right  is', self.root.rightchild.data)
        self.traverse_in_order(self.root)
        
def traverse_in_order(self,node):
    
    if node.leftchild!=None:  #there is leftchild
        print('node.leftchild is',node.leftchild.data )
        self.traverse_in_order(node.leftchild)       #go till end of leftnode
    print('')
    print('print node ', node.data)
    print('')
    if node.rightchild!=None:
        print('Node.RIght',node.rightchild.data)
        self.traverse_in_order(node.rightchild)
bst=BST()
bst.insert(32)
bst.insert(10)
bst.insert(1)
bst.insert(19)
bst.insert(46)

bst.traverse()

Output----

*****Traversing*****
   self.root is 32
   self.root.Left is 10
   self.root.Right  is 46
   node.leftchild is 10
   node.leftchild is 1
   -------------print node  1
   -------------print node  10
   Node.RIght 19
   print node  19
   print node  32
   Node.RIght 46
   print node  46

Can anyone help with traverse_in_order function.任何人都可以帮助 traverse_in_order function。 My doubt is from root we go till last left node and then print its data ie(1 is printed understood.)How 10 is printed again.Same with rights subtree.我的疑问是从根我们 go 直到最后一个左节点,然后打印其数据,即(1 被打印理解。)如何再次打印 10。与权利子树相同。 I hope you got what iam asking.我希望你明白我在问什么。 Thanks谢谢

"10" is not printed again. “10”不再打印。 The only prints that matter are the ones that say "print node", and those are all unique and in order.唯一重要的打印是那些说“打印节点”的打印,它们都是唯一且有序的。 The others are just debug prints to help you follow the logic.其他只是调试打印,以帮助您遵循逻辑。 They don't count.他们不算。

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

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