Help me understand Inorder Traversal without using recursion

后端 未结 14 2649
别跟我提以往
别跟我提以往 2020-12-12 11:44

I am able to understand preorder traversal without using recursion, but I\'m having a hard time with inorder traversal. I just don\'t seem to get it, perhaps, because I have

相关标签:
14条回答
  • 2020-12-12 12:49
    class Tree:
    
        def __init__(self, value):
            self.left = None
            self.right = None
            self.value = value
    
        def insert(self,root,node):
            if root is None:
                root = node
            else:
                if root.value < node.value:
                    if root.right is None:
                        root.right = node
                    else:
                        self.insert(root.right, node)
                else:
                    if root.left is None:
                        root.left = node
                    else:
                        self.insert(root.left, node)       
    
        def inorder(self,tree):
            if tree.left != None:
                self.inorder(tree.left)
            print "value:",tree.value
    
            if tree.right !=None:
                self.inorder(tree.right)
    
        def inorderwithoutRecursion(self,tree):
            holdRoot=tree
            temp=holdRoot
            stack=[]
            while temp!=None:
                if temp.left!=None:
                    stack.append(temp)
                    temp=temp.left
                    print "node:left",temp.value
    
                else:
                    if len(stack)>0:
                        temp=stack.pop();
                        temp=temp.right
                        print "node:right",temp.value
    
    0 讨论(0)
  • 2020-12-12 12:51

    Little Optimization of answer by @Emadpres

    def in_order_search(node):
        stack = Stack()
        current = node
    
        while True:
            while current is not None:
                stack.push(current)
                current = current.l_child
    
            if stack.size() == 0:
                break
    
            current = stack.pop()
            print(current.data)
            current = current.r_child
    
    0 讨论(0)
提交回复
热议问题