树的遍历算法
树的前序遍历
递归的方式:
class TreeNode:
def __init__(self,val):
self.val=val
self.left=None
self.right=None
def preorder(root):
if root==None:
return
print(root.val,end=' ')
preorder(root.left)
preorder(root.right)
非递归的方式:
思路:借助一个栈,当栈不为空时,从栈里面弹出一个节点,先把右节点压入栈,再把左节点压入栈
代码:
def preorder1(root):
if not root:
return
stack=[root]
while stack:
p=stack.pop()
print(p.val,end=' ')
if p.right:
stack.append(p.right)
if p.left:
stack.append(p.left)
树的中序遍历算法
递归的遍历方式:
def inorder(root):
if not root:
return
inorder(root.left)
print(root.val,end=' ')
inorder(root.right)
非递归的遍历方式:
思路:当前节点不为空,压入栈,向左走,当前节点为空,从栈中拿出一个打印,向左走
def inorder1(root):
if not root:
return
stack=[]
while stack or root:
if root!=None:
stack.append(root)
root=root.left
else:
root=stack.pop()
print(root.val,end=' ')
root=root.right
树的后序遍历算法
递归的遍历方式:
def postorder(root):
if not root::
return
postorder(root.left)
postorder(root.right)
print(root.val,end=' ')
非递归的遍历方式
思路:在前序遍历中,借助一个栈,先压右,再压左,是中左右,在后序遍历中,先压右再压左,即中右左,然后再借助一个栈中反向弹出就变成后序遍历的顺序:左右中了
代码:
def postorder1(root):
if not root:
return
stack=[root]
s=[]
while stack:
root=stack.pop()
s.append(root)
if root.left:
stack.append(root.left)
if root.right:
stack.append(root.right)
while s:
p=s.pop()
print(p.val,end=' ')
二叉树按层遍历
按层遍历在一行打印出来
def level_order(root):
queue=[root]
while queue:
root=queue.pop(0)
print(root.val,end=' ')
if root.left:
queue.append(root.left)
if root.right:
queue.append(root.right)
按层遍历按层打印出来
def level_order1(root):
cur_line=0
queue=[[root,cur_line]]
while queue:
root,line=queue.pop(0)
if line!=cur_line:
print()
cur_line=line
print(root.val,end=' ')
if root.left:
queue.append([root.left,cur_line+1])
if root.right:
queue.append([root.right,cur_line+1])