144. binary tree preorder traversal 解法

144. Binary Tree Preorder Traversal

Difficulty: Medium

Given a binary tree, return the preorder traversal of its nodes’ values.

Example:

1
2
3
4
5
6
7
8
Input: [1,null,2,3]
1

2
/
3

Output: [1,2,3]

Follow up: Recursive solution is trivial, could you do it iteratively?

解法

法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
   def preorderTraversal(self, root: TreeNode) -> List[int]:
       stack = []
       res = []
       if not root:
           return []
       stack.append(root)
       while len(stack) != 0:
           node = stack.pop()
           res.append(node.val)
           if node.right:
               stack.append(node.right)
           if node.left:
               stack.append(node.left)
       return res

法二

1
2
3
4
5
6
7
8
9
10
11
12
class :
def preorderTraversal(self, root: TreeNode) -> List[int]:
ans, st = [],[]
while root or st:
while root:
ans.append(root.val)
st.append(root)
root = root.left
root = st[-1].right
st.pop()

return ans