Leetcode 144.先序遍历

44. 二叉树的前序遍历

题目

给定一个二叉树,返回它的 前序 遍历。

1
2
3
4
5
6
7
8
9
10
示例:

输入: [1,null,2,3]
1
\
2
/
3

输出: [1,2,3]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

方法

方法1:递归

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

ans.append(root.val)
result=self.preorderTraversal(root.left)
result+=self.preorderTraversal(root.right)
return ans+result
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 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]
"""
ans=[]
def recursive(node):
if not node:
return None

ans.append(node.val)
recursive(node.left)
recursive(node.right)
recursive(root)
return ans

方法2:迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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):
# if not root:
# return []
stack = [root]
res = []
while stack:
node = stack.pop()
if node:
stack.append(node.right)
stack.append(node.left)
res.append(node.val)
return res
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(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]
"""
stack=[]
ans=[]
while root or stack:
while root:
ans.append(root.val)
stack.append(root.right)
root=root.left
root=stack.pop()
return ans
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
# 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]
"""
ans=[]
stack=[root]
while stack:
node=stack.pop()
if not node:
continue

ans.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return ans
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(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]
"""
ans=[]
stack=[root]
while stack:
node=stack.pop()
if node:
ans.append(node.val)
stack.append(node.right)
stack.append(node.left)
return ans

参考资料