DFS with level tracking 38 ms in Python


  • 0
    D
    # 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 level(self, root, lst, count):
            if(root == None):
                return
            
            if(len(lst) < count):
                lst.append([root.val])
                
            else:
                lst[count-1].append(root.val)
                
            self.level(root.left, lst, count+1)
            self.level(root.right, lst, count+1)
        
        
        
        def rightSideView(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            if(root == None):
                return []
                
            lst = []
            count = 0
            self.level(root, lst, count+1)
            ans = []
            for i in lst:
                print(i[len(i)-1])
                ans.append(i[len(i)-1])
                
            return ans

Log in to reply
 

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