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(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]] """ if root == None: return [] node_list = [] node_list.append(root) list_value = [] self.helper(node_list, list_value) return list_value def helper(self, node_list, list_value): tmp_l_value = [] tmp_l_node = [] if node_list != []: for i in node_list: tmp_l_value.append(i.val) if i.left != None: tmp_l_node.append(i.left) if i.right != None: tmp_l_node.append(i.right) list_value.append(tmp_l_value) self.helper(tmp_l_node, list_value)
#非递归,用队列解法
# 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]] """ if not root : return [] from collections import deque q_node = deque([root]) list_value = [] while q_node: tmp_value = [] size = len(q_node) for i in range(size): node = q_node.popleft() if node.left: q_node.append(node.left) if node.right: q_node.append(node.right) tmp_value.append(node.val) list_value.append(tmp_value) return list_value