How to change this to supprot Level Order Traversal II


  • 0
    C

    The following is easy to understand.
    And get a 60ms run time for Traversal quesiton I
    When it comes to Traversal II, I simply reverse the self.l1 before return. which is not efficient.
    Any suggestions??

    class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    def init(self):
    self.l1 = []

    def levelOrder(self, root):
        self.helper(root,0)
        return self.l1
        
    def helper(self,root,depth):
        if root is None: return None
        if len(self.l1)==depth: self.l1.append([root.val])
        else: self.l1[depth].append(root.val)
        self.helper(root.left,1+depth)
        self.helper(root.right,1+depth)

  • 0
    B

    instead using the append function, try insert function, which can insert into any position.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.