Queue based approach in Python


  • 0
    B
    # 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 rightSideView(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            
            
            view = list()
            if root is None:
                return view
            
            view.append(root.val)
            q = list()
            
            q.append(root)
            q.append(None)
            level = prevlevel = 0
            
            while len(q) > 0:
                n = q.pop(0)
                if n is None:
                    if len(q) > 0:
                        q.append(None)
                        level += 1
                else:
                    right = n.right
                    left = n.left
                    if right != None:
                        q.append(right)
                    if left != None:
                        q.append(left)
                    
                    if prevlevel != level:
                        view.append(n.val)
                        prevlevel = level
                    
                
            return view
    

Log in to reply
 

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