0%

LeetCode 144 | 二叉树的前序遍历

读前福利:几百本互联网技术书籍送给大家https://mp.weixin.qq.com/s/dFqVQ2qJxvQ0YrIlPISJuw


每天分享一个LeetCode题目,从简单到难,每天 5 分钟,一起进步

LeetCode 前序遍历,地址l:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/

树结点类

1
2
3
4
5
6
# 树结点类
class TreeNode(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right

递归遍历

这个是大家比较熟悉的一种方式了!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""

def pre_order(root):
if not root:
return
res.append(root.val)
pre_order(root.left)
pre_order(root.right)

res = []
pre_order(root)
return res

非递归遍历

非递归遍历需要自己设计一个栈进行临时结点存放

1.先访问根结点

2.然后判断有无右孩子,如果有右孩子,则入栈。否则,执行第 3 点

3.如果有左孩子,访问左孩子。否则,将栈顶元素弹出。继续进行第 2 点的判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def preorderTraversal_no_recursion(self, root):
if not root:
return []
s = [root] # 借助栈
res = [] # 结果存放的位置
while s:
res.append(root.val)
if root.right:
s.append(root.right)
if root.left:
root = root.left
else:
root = s.pop()
return res

完整代码

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# -*- coding:utf-8 -*-
# !/usr/bin/env python

# 树结点类
class TreeNode(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right


# url:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""

def pre_order(root):
if not root:
return
res.append(root.val)
pre_order(root.left)
pre_order(root.right)

res = []
pre_order(root)
return res

def preorderTraversal_no_recursion(self, root):
if not root:
return []
s = [root] # 借助栈
res = [] # 结果存放的位置
while s:
res.append(root.val)
if root.right:
s.append(root.right)
if root.left:
root = root.left
else:
root = s.pop()
return res


if __name__ == "__main__":
# 新建节点
root = TreeNode('A')
node_B = TreeNode('B')
node_C = TreeNode('C')
node_D = TreeNode('D')
node_E = TreeNode('E')
node_F = TreeNode('F')
node_G = TreeNode('G')
node_H = TreeNode('H')
node_I = TreeNode('I')
# 构建二叉树
# A
# / \
# B C
# / \ / \
# D E F G
# / \
# H I
root.left, root.right = node_B, node_C
node_B.left, node_B.right = node_D, node_E
node_C.left, node_C.right = node_F, node_G
node_D.left, node_D.right = node_H, node_I

s = Solution()
print(s.preorderTraversal(root))
print(s.preorderTraversal_no_recursion(root))

最后

在这里给大家准备了几百本的互联网技术类书籍,需要的来下载吧!点击获取
有任何问题,欢迎随时交流!!!

------ 全文结束------