二叉树的层次遍历
二叉树的层次遍历即从上往下、从左至右依次打印树的节点。
其思路就是将二叉树的节点加入队列,出队的同时将其非空左右孩子依次入队,出队到队列为空即完成遍历。
# -*- 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
outList=[]
queue=[root]
while queue!=[] and root:
outList.append(queue[0].val)
if queue[0].left!=None:
queue.append(queue[0].left)
if queue[0].right!=None:
queue.append(queue[0].right)
queue.pop(0)
return outList
在python中,队列是用列表来模拟的,其中pop(0)的操作复杂度是O(n),下面不用队列作为改进。
def PrintFromTopToBottom(self, root):
if not root:
return []
currentStack = [root]
outList= []
while currentStack:
nextStack = []
for point in currentStack:
if point.left:
nextStack.append(point.left)
if i.right:
nextStack.append(point.right)
outList.append(point.val)
currentStack = nextStack
return outList
二叉树的按层输出
二叉树的按层输出即从上往下、从左至右依次打印树的节点。每一层输出一行。
这一题和上一题的区别主要在于要区别开每一层,即不仅按层遍历还要按层输出。难点在于有的层会缺项,即不是完全二叉树。但根据层次遍历的特点,节点会按层依次的进入队列,利用这一特点来区分每一层。
上面问题改进版中即是按层存储在每一个列表中的,也适合解决该问题
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表[[0],[1,2],[4,5]]
def Print(self, pRoot):
# write code here
if not pRoot:
return []
queue=[pRoot]
outList=[]
while queue:
res=[]
nextQueue=[]
for point in queue: #这里再遍历每一层
res.append(point.val)
if point.left:
nextQueue.append(point.left)
if point.right:
nextQueue.append(point.right)
outList.append(res)
queue=nextQueue #这一步很巧妙,用当前层覆盖上一层
return outList
当然,完全用队列来做也是没有问题的,不过,其关键在于确认每一层的分割点,因此可以用一个标志位来记录这个分割点的位置
def Print(self, pRoot):
# write code here
if not pRoot:
return []
queue=[pRoot]
outList=[]
while queue:
res=[]
i=0
numberFlag=len(queue) #这一步记录当前层中节点的个数
while i <numberFlag: #这里再遍历每一层
point=queue.pop(0)
res.append(point.val)
if point.left:
queue.append(point.left)
if point.right:
queue.append(point.right)
i+=1
outList.append(res)
return outList