Pre-order to post-order traversal

后端 未结 11 1452
挽巷
挽巷 2020-12-23 21:56

If the pre-order traversal of a binary search tree is 6, 2, 1, 4, 3, 7, 10, 9, 11, how to get the post-order traversal?

11条回答
  •  礼貌的吻别
    2020-12-23 22:48

    Here is full code )

    class Tree:
        def __init__(self, data = None):
            self.left = None
            self.right = None
            self.data = data
    
        def add(self, data):
            if self.data is None:
                self.data = data
            else:
                if data < self.data:
                    if self.left is None:
                        self.left = Tree(data)
                    else:
                        self.left.add(data)
                elif data > self.data:
                    if self.right is None:
                        self.right = Tree(data)
                    else:
                        self.right.add(data)
        def inOrder(self):
            if self.data:
                if self.left is not None:
                    self.left.inOrder()
                print(self.data)
                if self.right is not None:
                    self.right.inOrder()
    
        def postOrder(self):
            if self.data:
                if self.left is not None:
                    self.left.postOrder()
                if self.right is not None:
                    self.right.postOrder()
                print(self.data)
    
        def preOrder(self):
            if self.data:
                print(self.data)
                if self.left is not None:
                    self.left.preOrder()
                if self.right is not None:
                    self.right.preOrder()
    arr = [6, 2, 1, 4, 3, 7, 10, 9, 11]
    root = Tree()
    for i in range(len(arr)):
        root.add(arr[i])
    print(root.inOrder())
    

提交回复
热议问题