LeetCode_Binary Tree Preorder Traversal

Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes’ values.
(先序遍历二叉树)

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

Example:



1. 递归

具体实现方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 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 helper(self, root, res):
if not root:
return res
res.append(root.val)
self.helper(root.left, res)
self.helper(root.right, res)

def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []

result = []
self.helper(root, result)

return result

2. 迭代 & 栈

先将访问根节点,然后将右子树节点加入到栈中,然后访问左子树。具体实现方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 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]
"""
if not root:
return []

result, stack = [], []
p = root
while stack or p:
if p:
result.append(p.val)
stack.append(p.right)
p = p.left
else:
p = stack.pop()

return result
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []

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

return result