# -*- coding:utf-8 -*-
"""
Author: leadingme
Mail:[email protected]
MyWebsite:leadingme.top
"""
# 二叉树的层次遍历
"""
算法要求:
给定一颗二叉树,返回其按层次遍历的节点值(逐层地,从左到右访问所有节点)
示例:
输入: 3
/ \
9 20
/ \
15 7
输出: [[3],[9,20],[15,7]]
解题思路:
以层为单位操作,数的层数越深,节点就越多,且对顺序有要求,所以可以对层进行迭代
"""
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrder(self, root: TreeNode) ->list:
rList = [] # 用来保存最终返回的节点值数组
subList = [] # 暂时存储上一层节点值
if root is None:
return rList
else:
cNodeList = [root] # 上一层节点数组
nNodeList = [] # 下一层节点数组
while True:
if cNodeList: #
node = cNodeList.pop(0) # 弹出上一层节点数组的第一个值
subList.append(node.val)
if node.left and node.right: # 上一层的节点拥有左右节点,则把它的左右节点加入到下一层节点数组中
nNodeList.append(node.left)
nNodeList.append(node.right)
elif node.left: # 上一层的节点只拥有左节点,则把它的左节点加入到下一层节点数组中
nNodeList.append(node.left)
elif node.right: # 上一层的节点只拥有右节点,则把它的右节点加入到下一层节点数组中
nNodeList.append(node.right)
else:
pass
else:
# 这里的subList[:]中用到的[:]类似于深度拷贝,改变原数组值,不会影响它,有关知识可以看以下链接
rList.append(subList[:]) # 将sublist的值(上一层节点的值)赋值给rList
subList = [] # 置空
if not nNodeList:
break
else:
cNodeList = nNodeList[:]
nNodeList = []
return rList
list[:]深度拷贝用法:
https://www.jianshu.com/p/88f4b426d18d