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 7return its level order traversal as:
[ [3], [9,20], [15,7] ]
解题思路:该题的目的是做层序遍历,使用宽度优先搜索(BST),用一个队列queue保存一层的结点,通过遍历queue,取得该层结点的value值,并且在new_q里同步保存下一层结点
class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] queue = [root] result = [] while(queue): level = [] new_q = [] for i in queue: node = i #保存每一层结点的value level.append(node.val) #将下一层的结点保存在new_q队列,当queue队列遍历结束后赋值给queue if(node.left): new_q.append(node.left) if(node.right): new_q.append(node.right) queue = new_q result.append(level) return result