0

I am trying to implement a python code to find the depth of a binary tree. I have successfully implemented the C++ version but when I implement the same code in python it is giving a different answer in Leetcode. C++ version:

class Solution {
public:
    int maxDepth(TreeNode* root) {

        if(!root) return 0;
        int l=maxDepth(root->left);
        int r=maxDepth(root->right);
        return 1 + max(l, r); 
    }

Python version:

class Solution(object):
    def maxDepth(self, root):

        if root is None:
                  return 0           
        self.left=self.maxDepth(root.left)     
        self.right=self.maxDepth(root.right)        
        return max(self.left,self.right) +1

Is there any fundamental difference in how recursive calls are made in Python and C++. My python code fails for the following case:[1,2,3,4,5]

1 Answers1

0

Your code is not identical. self.left means that you are modifying a field of Solution object in case of Python (cf. .Explaining the python 'self' variable to a beginner). To use local variables forgo the use of self prefix.

lukeg
  • 4,189
  • 3
  • 19
  • 40
  • Thank you very much for the answer. I have used C++ most of my time and have just started using Python so I am little weak in the details of it. Really appreciate your help :) – Gautam Sharma Jan 09 '20 at 15:17