A.二叉树的层序遍历
题意: 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回结果:
[
[3],
[9,20],
[15,7]
]
思路: 用队列实现,将二叉树中每一层结点放在队列里并记下二叉树中每一层的结点个数temp,temp个结点出队列的同时,把结点的左右子结点(下一层结点)加入队列。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
queue = [root] #根结点入队列
res =