Has anyone tried to use python to solve this question?


  • 0
    H

    Follow is my code:

    class Solution:
    # @param root, a tree node
    # @return a list of integers
    def preorderTraversal(self, root,result=[]):
        if root==None:
            return result
        else:
            result.append(root.val)
        Solution.preorderTraversal(self,root.left,result)
        Solution.preorderTraversal(self,root.right,result)
        return result
    


    On OJ,when run with {1,2},it will return [1,1,2].

    But it can work out with the right answer([1,2]) on my computer.

    Can anyone tell me why?


  • 0
    M
    class Solution:
        # @param root, a tree node
        # @return a list of integers
        def preorderTraversal(self, root):
            if root == None:
                return []
            return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)

  • 0
    H

    Could you please tell me which part goes wrong in my code?


  • 0
    H

    Hi, I have tested your code on my computer, it turned out that it worked properly. I have no idea why it didn't get accepted.

    I have write my own code as follow, and it works:

    class Solution:

    # @param root, a tree node
    # @return a list of integers
    
    def preorderTraversal(self, root):
        ans = []
        return self.helper(root,ans)
        
    def helper(self, root, ans):
        if root:
            ans.append(root.val)
            self.helper(root.left, ans)
            self.helper(root.right,ans)
        return ans
    

    but as the problem states, we'd better solve it without recursion, following is my accepted non-recursion code:

    class Solution:

    # @param root, a tree node
    # @return a list of integers
    
    def preorderTraversal(self, root):
        if not root:
            return []
        stack = []
        ans = []
        stack.append(root)
        while stack:
            tmp = stack.pop()
            if tmp:
                ans.append(tmp.val)
            if tmp.right:
                stack.append(tmp.right)
            if tmp.left:
                stack.append(tmp.left)
        return ans

  • 0
    H

    3q very much


Log in to reply
 

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