二叉树的前序遍历
class TreeNode():
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Solution():
#递归
def preorder_digui(self,root):
res = []
def helper(root):
if not root:
return
res.append(root.val)
helper(root.left)
helper(root.right)
helper(root)
return res
#迭代
def preorder_iter(self,root):
res = []
if not root:
return res
stack = [root]
while stack:
node = stack.pop()
res.append(node.val)
if root.right:
stack.append(root.right)
if root.left:
stack.append(root.left)
return res
二叉树的中序遍历
中序遍历是先遍历左子树,再根节点,最后右子树。 迭代过程可以用一个指针模拟这个过程:将节点的左节点不断地压入栈中,直到没有左节点为止(dfs),然后弹出栈顶元素,若该元素有右节点, 则对右节点做同样的寻找左节点的操作;没有的话就继续弹出栈顶元素,直到栈为空。
class Solution():
#递归
def inorder_digui(self,root):
res = []
def helper(root):
if not root:
return
helper(root.left)
res.append(root.val)
helper(root.right)
helper(root)
return res
#迭代
def inorder_iter(self,root):
res = []
if not root:
return res
stack =[]
p = root
while stack or p:
while p:
stack.append(p)
p = p.left
p = stack.pop()
res.append(p.val)
p = p.right
return res
二叉树的后序遍历
class Solution():
#递归
def postorder_digui(self,root):
res = []
def helper(root):
if not root:
return
helper(root.left)
helper(root.right)
res.append(root.val)
helper(root)
return res
#迭代
def postorder_iter(self,root):
res = []
if not root:
return res
stack =[root]
while stack:
node = stack.pop()
res.append(node.val)
if root.left:
stack.append(root.left)
if root.right:
stack.append(root.right)
return res[::-1]
前中后遍历迭代法的统一写法
class Solution:
"""
为了解决遍历节点和节点值加入结果集不一致的问题
将当前节点入栈时,添加一个空节点作为标记
当遍历到空节点,表明需要加入结果集
"""
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
if not root:
return res
stack = [root]
while stack:
if stack[-1] != "null":
node = stack.pop()
# 右节点入栈
if node.right:
stack.append(node.right)
# 根节点入栈,添加空节点标记
stack.append(node)
stack.append("null")
# 左节点入栈
if node.left:
stack.append(node.left)
else:
# 遇到空节点,先弹出空节点,再将节点值放入结果集
stack.pop()
res.append(stack.pop().val)
return res
二叉树的层序遍历
def cengciorder(root):
res = []
if not root:
return res
queue = [root]
while queue:
tmp = []
tmpqueue = []
for i in queue:
tmp.append(i.val)
if i.left:
tmpqueue.append(i.left)
if i.right:
tmpqueue.append(i.right)
res.append(tmp)
queue = tmpqueue
return res
写法二:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
if not root:
return []
ans = []
queue = [root]
while queue:
node = queue.pop(0)
ans.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return ans