版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.youkuaiyun.com/songyunli1111/article/details/81706801 </div>
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-cd6c485e8b.css">
<div id="content_views" class="markdown_views">
<!-- flowchart 箭头图标 勿删 -->
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>
</svg>
<h4 id="二叉树的层次遍历">二叉树的层次遍历</h4>
二叉树的层次遍历即从上往下、从左至右依次打印树的节点。
其思路就是将二叉树的节点加入队列,出队的同时将其非空左右孩子依次入队,出队到队列为空即完成遍历。
# -*- 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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
在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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
二叉树的按层输出
二叉树的按层输出即从上往下、从左至右依次打印树的节点。每一层输出一行。
这一题和上一题的区别主要在于要区别开每一层,即不仅按层遍历还要按层输出。难点在于有的层会缺项,即不是完全二叉树。但根据层次遍历的特点,节点会按层依次的进入队列,利用这一特点来区分每一层。
上面问题改进版中即是按层存储在每一个列表中的,也适合解决该问题
# -*- 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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
当然,完全用队列来做也是没有问题的,不过,其关键在于确认每一层的分割点,因此可以用一个标志位来记录这个分割点的位置
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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-258a4616f7.css" rel="stylesheet">
</div>