Python preorder iterative


  • 0
    A
    
    class Solution(object):
        def sortedArrayToBST(self, nums):
            """
            :type nums: List[int]
            :rtype: TreeNode
            
            """
            if not nums: return None
            
            l = 0
            r = len(nums)
            m = (l+r)/2
            root = TreeNode(nums[m])
            stack = [(root,l,m,r)]
            while stack:
                node, l, m, r = stack.pop()
                if r!=m+1:
                    node.right = TreeNode(nums[(r+m+1)/2])
                    stack.append((node.right,m+1,(r+m+1)/2,r))
                if l!=m:
                    node.left = TreeNode(nums[(l+m)/2])
                    stack.append((node.left,l,(l+m)/2,m))
                    
            return root
    

Log in to reply
 

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