LeetCode:102. Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[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 Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
if (root != None):
queue = []
queue.append(root)
while(len(queue) > 0):
item = []
tmp = []
while(len(queue) > 0):
x = queue.pop(0)
if(x.left != None):
tmp.append(x.left)
if(x.right != None):
tmp.append(x.right)
item.append(x.val)
res.append(item)
queue = tmp
return res
THE END.