以中序遍历为例:
递归:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
result = []
self.preorder(root, result)
return result
def preorder(self, root, result):
if root == None:
return
else:
self.preorder(root.left, result)
result.append(root.val)
self.preorder(root.right, result)
return
迭代:颜色法,白色代表未遍历到的节点,灰色代表已经遍历到的节点
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
white = 0
gray = 1
res = []
stack = [(white, root),]
while stack:
color, root = stack.pop()
if root is None: continue #判断节点是否为空
if color == white:
stack.append((white, root.right)) #其他顺序遍历只需要改变入栈顺序即可
stack.append((gray, root))
stack.append((white, root.left))
else:
res.append(root.val)
return res