题目描述:
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
返回其层次遍历结果:[[3],[9,20],[15,7]]
知识点:
思路和代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Node():
def __init__(self,data,next=None):
self.data = data
self.next=next
class myque():
def __init__(self):
self.length=0
self.left=None
self.right=None
def is_empty(self):
return self.left==None # 根据左侧节点判断队列是否为空
def enque(self,value):
self.length+=1
nd = Node(value)
if not self.left:
self.left=nd
self.right=nd
else:
self.right.next=nd
self.right=nd
def deque(self):
if self.left: # 根据左侧节点判断队列是否为空
r = self.left
self.left=self.left.next
self.length-=1
return r.data
else:
raise ValueError('empty queue!')
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return
res=[]
temp_queue=myque()
temp_queue.enque(root)
while not temp_queue.is_empty():
layer_res=[]
for i in range(temp_queue.length):
curr=temp_queue.deque()
layer_res.append(curr.val)
if curr.left:
temp_queue.enque(curr.left)
if curr.right:
temp_queue.enque(curr.right)
res.append(layer_res)
return res