Level order traversal - Iterative


  • 0
    A
    # 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 maxDepth(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if not root:
                return 0
            st = []
            st.append(root)
            aux = []
            level = 0
            while st:
                curr = st.pop(0)
                if curr.left:
                    aux.append(curr.left)
                if curr.right:
                    aux.append(curr.right)
                if not st:
                    level+=1
                    st = aux[::]
                    aux = []
            return level
                
                
    

Log in to reply
 

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