【Python】二叉树遍历非递归算法

class Node:
	def __init__(self, num):
		self.left = None
		self.right = None
		self.val = num

1. 先序遍历

根左右

def	inOrderTraverse(root):
	p, stack = root, []
	res = []
	while p or len(stack) != 0:
		if p:
			stack.append(p)
			res.append(p.val)
			p = p.left
		else:
			temp = stack.pop()
			if temp.right:
				p = temp.right
	return res		

2. 中序遍历

左根右

def	preOrderTraverse(root):
	p, stack = root, []
	res = []
	while p or len(stack) != 0:
		if p:
			stack.append(p)
			p = p.left
		else:
			temp = stack.pop()
			res.append(temp.val)
			if temp.right:
				p = temp.right
	return res		

3. 后序遍历

左右根

def	postOrderTraverse(root):
	res, stack = [], []
	temp, p = None, root
	while p or len(stack) != 0:
		if p:
			stack.append(p)
			p = p.left
		else:
			p = stack[-1]
			if p.right and p.right != temp: # 记录右子树是否被访问过
				p = p.right
			else:
				temp = stack.pop() 
				res.append(temp.val)
				p = None
	return res		

4. 层序遍历

插播

def	levelOrderTraverse(root):
	res, queue = [], [root]
	while queue:
		n = len(queue)
		for i in range(n):
			cur = queue.pop()
			res.append(cur.val)
			if cur.left:
				queue.insert(0, cur.left)
			if cur.right:
				queue.insert(0, cur.right)
	return res		

你可能感兴趣的:(LeetCode,leetcode,二叉树,算法)