Why my Java code is accepted while my Python code is not?


  • 0
    J

    After I had my Java code accepted, I tried to solve this problem in Python and it gave me wrong answer. Can anyone tell me the difference between my Java code and my Python code and what goes wrong in my Python code?

    Here's my Java code, it's accepted:

    public class Solution {
        private static TreeNode tail;
        public void flatten(TreeNode root) {
            if (root == null) return;
            tail = root;
            if (root.left != null) {
                TreeNode right = root.right;
                root.right = recurFlatten(root.left);
                root.left = null;
                TreeNode tempTail = tail;
                tempTail.right = recurFlatten(right);
            }
            else {
                root.right = recurFlatten(root.right);
            }
        }
        
        private TreeNode recurFlatten(TreeNode root) {
            if (root == null) return null;
            tail = root;
            if (root.left != null) {
                TreeNode right = root.right;
                root.right = recurFlatten(root.left);
                root.left = null;
                TreeNode tempTail = tail;
                tempTail.right = recurFlatten(right);
            }
            else {
                root.right = recurFlatten(root.right);
            }
            return root;
        }
    }
    

    And here's my Python code, when the input is {1, 2}, it gives {1} as output and the correct answer should be {1, #, 2}:

    class Solution:
        # @param root, a tree node
        # @return nothing, do it in place
        tail = TreeNode(-1)
        def flatten(self, root):
            if root is None:
                return
            tail = root
            if root.left is not None:
                right = root.right
                root.right = self.recurFlatten(root.left)
                root.left = None
                tempTail = tail
                tempTail.right = self.recurFlatten(right)
            else:
                root.right = self.recurFlatten(root.right)
        def recurFlatten(self, node):
            if node is None:
                return None
            tail = node
            if node.left is not None:
                right = node.right
                node.right = self.recurFlatten(node.left)
                node.left = None
                tempTail = tail
                tempTail.right = self.recurFlatten(right)
            else:
                node.right = self.recurFlatten(node.right)
            return node

  • 0
    J

    Alright guys, as my godlike friend pointed out, I should use Solution.tail instead of tail in my Python code.

    This is a stupid mistake from a Python newbie T.T


Log in to reply
 

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