Post-order traversal of Leetcode binary tree

0 topic description

Leetcode original title link: post-order traversal of binary tree
Insert picture description here

Post-order traversal of binary tree: traverse the tree in the way of visiting the left subtree-right subtree-root node, and when visiting the left subtree or the right subtree, we traverse the same way until the traversal is complete Tree. Therefore, the entire traversal process is naturally recursive, and we can directly simulate this process with a recursive function.

1 Recursive solution

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        if not root: 
            return []
        return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]

Algorithm complexity
Time complexity: O (n) O(n)O ( n ) , wherennn is the number of binary tree nodes. In the traversal of the binary tree, each node will be visited once and only once.
Space complexity:O (n) O(n)O ( n ) . The space complexity depends on the recursive stack depth, and the stack depth can reachO (n) O(n)when the binary tree is a chainO ( n ) level.

2 Iterative solution (stack)

We can also implement the recursive function of Method 1 in an iterative manner. The two methods are equivalent. The difference is that a stack is implicitly maintained during recursion, and we need to explicitly simulate this stack during iteration. , The rest of the implementation and details are the same, you can refer to the following code for details.

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        White, Gray = 0, 1
        res = []
        stack = [(White, root)]
        while stack:
            color, node = stack.pop()
            if not node: continue
            if color == White:
                stack.append((Gray, node))
                stack.append((White, node.right))
                stack.append((White, node.left))
            else:
                res.append(node.val)
        return res

Algorithm complexity
Time complexity: visit each node exactly once, time complexity is O (N) O (N)O ( N ) , whereNNN is the number of nodes, which is the size of the tree.
Space complexity: depends on the structure of the tree, the worst case is to store the entire tree, so the space complexity isO (N) O(N)O ( N )

3 Morris postorder traversal

There is a clever way to achieve post-order traversal in linear time and only occupy a constant space. This method is Morris traversal.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        def addPath(node: TreeNode):
            count = 0
            while node:
                count += 1
                res.append(node.val)
                node = node.right
            i, j = len(res) - count, len(res) - 1
            while i < j:
                res[i], res[j] = res[j], res[i]
                i += 1
                j -= 1

        if not root: return []
        node, res = root, []
        while node:
            pre = node.left
            if pre:
                while pre.right and pre.right is not node:
                    pre = pre.right
                if not pre.right:
                    pre.right = node
                    node = node.left
                    continue
                else:
                    pre.right = None
                    addPath(node.left)
            node = node.right

        addPath(root)
        return res

Algorithm complexity
Time complexity: O (n) O(n)O ( n ) , wherennn is the number of nodes in the binary tree. Nodes without a left subtree are visited only once, and nodes with a left subtree are visited twice.
Space complexity:O (1) O(1)O ( 1 ) . Only the pointers that already exist (the free pointers of the tree) are manipulated, so only constant extra space is needed.

Reference

Pre-order traversal of binary tree Middle- order traversal of
binary tree-Python implements three solutions

Guess you like

Origin blog.csdn.net/OuDiShenmiss/article/details/109251426