1. 二叉树遍历
1.1. 题目描述
复习一下二叉树的三种遍历方式,前序、中序、后序
本题以中序为例,说明一下两种写法
1.2. 代码
- 递归
def solution(root):
if not root:
return []
return solution(root.left) + [root.val] + solution(root.right)
- 栈
def solution(root):
WHITE, GRAY = 0, 1
stack = [(WHITE, root)]
ans = []
while stack:
color, node = stack.pop()
if node is None:
continue
if not color:
stack.append((WHITE, node.right))
stack.append((GRAY, node))
stack.append((WHITE, node.left))
else:
ans.append(node.val)
return ans