# C++ accepted, but Python not

• Below is my C++ solution, 12ms:

``````class Solution {
public:
vector<int> item;
vector<vector<int> > res;
int dfs(TreeNode* root, int sum) {
if(root == NULL)return 0;
if(root->left == NULL && root->right == NULL && root->val == sum) {
item.push_back(root->val);
res.push_back(item);
item.pop_back();
}
else {
item.push_back(root->val);
dfs(root->left, sum - root->val);
dfs(root->right, sum - root->val);
item.pop_back();
}
return 0;
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
dfs(root, sum);
return res;
}
};
``````

When I write the same DFS in Python, it's WA! How wired!
Can any one point out where am I wrong?
I change sum to sum1, because sum is a function in python, I suggest the default code snippet should be modified.

``````class Solution:
# @param root, a tree node
# @param sum1, an integer
# @return a list of lists of integers
item = []
res = []
def dfs(self, root, sum1):
# leaf reached
if root == None:
return 0
if root.left == None and root.right == None and sum1 == root.val:
self.item.append(root.val)
self.res.append([x for x in self.item])
self.item.pop()
else:
self.item.append(root.val)
self.dfs(root.left, sum1 - root.val)
self.dfs(root.right, sum1 - root.val)
self.item.pop()
return 0
def pathSum(self, root, sum1):
self.dfs(root, sum1)
return self.res``````

• I made some changes to your code. Add initialization of self.res and self.item before calling dfs.
see blow.

``````class Solution:
# @param root, a tree node
# @param sum1, an integer
# @return a list of lists of integers
***#    item = []
#    res = []***
def dfs(self, root, sum1):
# leaf reached
if root == None:
return 0
if root.left == None and root.right == None and sum1 == root.val:
self.item.append(root.val)
self.res.append([x for x in self.item])
self.item.pop()
else:
self.item.append(root.val)
self.dfs(root.left, sum1 - root.val)
self.dfs(root.right, sum1 - root.val)
self.item.pop()
return 0
def pathSum(self, root, sum1):
***self.item = []
self.res = []***
self.dfs(root, sum1)
return self.res``````

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