思路:

1. 使用列表保存结果;

2. 使用栈(列表实现)存储结点;

3. 当根结点存在,保存结果,根结点入栈;

4. 将根结点指向左子树;

5. 根结点不存在,栈顶元素出栈,并将根结点指向栈顶元素的右子树;

6. 重复步骤3-6,直到栈空。

LeetCode: 144. Binary Tree Preorder Traversal

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        ret = []
        stack = []
        while root or stack:
            while root:
                ret.append(root.val)
                stack.append(root)
                root = root.left
            if stack:
                t = stack.pop()
                root = t.right
        return ret

相关文章:

  • 2021-11-04
  • 2022-12-23
  • 2021-12-03
  • 2021-11-19
  • 2022-01-14
  • 2022-01-15
  • 2021-08-05
  • 2021-12-06
猜你喜欢
  • 2021-12-29
  • 2021-06-10
  • 2021-12-03
  • 2021-12-10
  • 2021-11-04
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案