二叉树
- 深度优先遍历方式
- 先序遍历: r o o t → l e f t → r i g h t root \rightarrow left \rightarrow right root→left→right
- 中序遍历: l e f t → r o o t → r i g h t left \rightarrow root \rightarrow right left→root→right 二叉搜索树
- 后序遍历:
l
e
f
t
→
r
i
g
h
t
→
r
o
o
t
left \rightarrow right \rightarrow root
left→right→root 删除节点的顺序
- 代码(以中序遍历为例)
- 递归
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def helper(root):
if root is None:
return
helper(root.left)
res.append(root.val)
helper(root.right)
helper(root)
return res
- 迭代: 颜色标记法,white,gray分别代表访问一次的结点和再次访问的结点
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
white, gray = 0, 1
res = []
stack = [(white, root),]
while stack:
color, node = stack.pop()
if node is None:
continue
if color == white:
stack.extend([(white, node.right), (gray, node), (white, node.left)])
else:
res.append(node.val)
return res
详见
- BFS层次遍历方式
class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
res,cur_level = [],[root]
while cur_level:
temp = []
next_level = []
for i in cur_level:
temp.append(i.val)
if i.left:
next_level.append(i.left)
if i.right:
next_level.append(i.right)
res.append(temp)
cur_level = next_level
return res