Exemple #1
0
def test1():
    """
	测试栈
	:return:
	"""
    stack = Stack()
    stack.push(3)
    stack.push(6)
    stack.push(9)
    stack.push(12)
    # 12,9,6,3,
    print(stack)
    # 12
    print(stack.pop())
    # 9,6,3,
    print(stack)
    # 9
    print(stack.top())
Exemple #2
0
    def preorder_traversal(self) -> List[T]:
        """
		前序
		:return:
		"""
        if self._root is None:
            return []

        container = []
        stack = Stack()
        stack.push(self._root)

        while not stack.is_empty():
            node = stack.pop()
            container.append(node.element)
            # if cmp(node.element): break
            if node.right is not None:
                stack.push(node.right)
            if node.left is not None:
                stack.push(node.left)
        return container
Exemple #3
0
    def inorder_traversal(self) -> List[T]:
        """
		中序遍历
		:return:
		"""
        if self._root is None:
            return

        container = []
        stack = Stack()
        curr = self._root
        while curr or not stack.is_empty():
            if curr is not None:
                stack.push(curr)
                curr = curr.left
            else:
                node = stack.pop()
                container.append(node.element)
                curr = node.right
        return container
Exemple #4
0
    def postorder_traversal(self) -> List[T]:
        """
		后序遍历
		:return:
		"""
        if self._root is None:
            return

        container = []
        stack = Stack()
        stack.push(self._root)
        prev = None
        while not stack.is_empty():
            # 取出栈最顶端的元素
            node = stack.top()
            if node.is_leaf() or (prev and prev.parent == node):
                prev = stack.pop()
                container.append(prev.element)
            else:
                if node.right is not None:
                    stack.push(node.right)
                if node.left is not None:
                    stack.push(node.left)
        return container
from com.jqc.stack.stack import Stack

if __name__ == '__main__':
    # test1()
    # test2()
    # test3()
    stack = Stack()
    stack.push(3)
    stack.push(6)
    stack.push(9)
    stack.push(12)
    # 12,9,6,3,
    print(stack)
    # 12
    print(stack.pop())
    # 9,6,3,
    print(stack)
    # 9
    print(stack.top())