The trick is to add a parameter to indicate the level.
Solution:
# T:O(n) S:O(n) class Solution: # @param root, a tree node # @return a list of lists of integers def preorder(self, root, level, res): if root: if len(res) < level+1: res.append([]) res[level].append(root.val) self.preorder(root.left, level+1, res) self.preorder(root.right, level+1, res) def levelOrder(self, root): res=[] self.preorder(root, 0, res) return resRun Time: 68 ms
No comments:
Post a Comment