Help! Works in C++, but not in Python...?


  • 1
    Z

    My answer works in C++, but it was wrong in Python. Could someone please help?? Thanks a lot!!

        bool isSameTree(TreeNode *p, TreeNode *q) {
              if (!p || !q) return p == q;
              else 
              return (p->val == q->val) && isSameTree(p->left,q->left) && isSameTree(p->right,q->right); }
    

    The above works. However, I don't know what's wrong with my Python code:

      def isSameTree(self, p, q):
            if p == None or q == None: 
                return p == q 
            else: 
                return p.val == q.val and self.isSameTree(p.left,q.left) and self.isSameTree(q.right, p.right)
    

    OJ says Runtime Error


  • 2
    S
    def isSameTree(self, p, q):
            if p is None or q is None:  # if p == None or q == None: 
                return p == q 
            else: 
                return p.val == q.val and self.isSameTree(p.left,q.left) and self.isSameTree(q.right, p.right)
    

  • 0
    Z

    You're amazing!!
    I didn't know I cannot use "==" as test condition in Python...


  • 0
    Y

    I am not sure that "==" does work here, because I simply tried the code and it was accepted.


Log in to reply
 

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