Python Preorder solution


  • 0
    H
    class Solution(object):
        def boundaryOfBinaryTree(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            found=[False,False]
            mp={}
            def getleft(root,res):
                res.append(root.val)
                mp[root]=1
                if not root.left and not root.right:
                    found[0]=True
                if root.left!=None and not found[0]:
                    getleft(root.left,res)
                if root.right!=None and not found[0]:
                    getleft(root.right,res)
    
            def getright(root,res):
                if not mp.has_key(root):
                    res.append(root.val)
                    mp[root]=1
                if not root.left and not root.right:
                    found[1]=True
                if root.right!=None  and not found[1]:
                    getright(root.right,res)
                if root.left!=None  and not found[1]:
                    getright(root.left,res)
    
            def getbottom(root,res):
                if not root: return
                if not root.left and not root.right:
                    if not mp.has_key(root):
                        res.append(root.val)
                        mp[root]=1
                getbottom(root.left,res)
                getbottom(root.right,res)
    
            res,resl,resr,resb=[],[],[],[]
    
            if not root: return []
            if not root.left: 
                resl.append(root.val)
                mp[root]=1
            else: getleft(root,resl)
            if not root.right:
                if not mp.has_key(root):
                    resr.append(root.val)
                    mp[root]=1
            else:getright(root,resr)
            
            getbottom(root,resb)
            resr=resr[::-1]
            res=resl+resb+resr
    
            return res

Log in to reply
 

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