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] ]
Sol 1:
iteration.
Append nodes of current level to a tmp variable. Then if next level has nodes, append them to the next level. Then advance current level to next level. Store the current level to tmp variable before overwritten by the next level.
# 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]] """ # iteration. Time O(n), space O(1) # The next level is put in a list. Loop until all levels are added. if not root: return [] currentLevel= [root] output = [] while currentLevel: tmp = [] for x in currentLevel: tmp.append(x.val) output.append(tmp) nextLevel = [] for x in currentLevel: if x.left: nextLevel.append(x.left) if x.right: nextLevel.append(x.right) currentLevel = nextLevel return output
Sol 2 :
Recursion. DFS.
# 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]] """ # recursion. Time O(n) Space O(n) # better to use iteration in the problem. Iteration: Time O(n) Space(1) result = [] # have to input which level to start self.level_dfs(root, 0 , result) return result # since recursion is based on the previous result, then result must be in the input of a dfs method def level_dfs(self, node, level, result): if not node: return # the length check is neccessay, otherwise the final append will be out of range. if level == len(result): result.append([]) if node.left: self.level_dfs(node.left, level + 1, result) if node.right: self.level_dfs(node.right, level + 1, result) result[level].append(node.val)
Similar Problem:
1 Tree Level Order Print