Preorder Traversal

前序遍历有两种,一种是用栈做辅助结构的迭代算法,另外一种是Morris Travesal

  • Stack algorithm
class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []

        stack, res = [root], []
        while stack:
            node = stack.pop()
            res.append(node.val)
            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)

        return res
  • Morris Preorder Traversal
class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        pre, cur = root, None
        res = []

        while pre:
            cur = pre.left
            if cur:
                while cur.right and cur.right != pre:
                    cur = cur.right
                if not cur.right:
                    cur.right = pre
                    res.append(pre.val)
                    pre = pre.left
                    continue
                else:
                    cur.right = None
            else:
                res.append(pre.val)
            pre = pre.right

        return res

results matching ""

    No results matching ""