In LeetCode problem Path Sum 2
, one Python solution writes:
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
res = []
self.helper(root, sum, res, [])
return res
def helper(self, root, target, res, temp):
if not root:
return
if not root.left and not root.right and root.val == target:
res.append(list(temp+[root.val]))
return self.helper(root.left, target - root.val, res, temp+[root.val]) or self.helper(root.right, target - root.val, res, temp+[root.val])
Clearly this answer is not wrong. But what puzzles me is the usage of or
in the last line. The function is not a Boolean type. Is it alright to use or
here?
Also one C++ answer is here:
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int>> res;
vector<int> out;
helper(root, sum, out, res);
return res;
}
void helper(TreeNode* node, int sum, vector<int>& out, vector<vector<int>>& res) {
if (!node) return;
out.push_back(node->val);
if (sum == node->val && !node->left && !node->right) {
res.push_back(out);
}
helper(node->left, sum - node->val, out, res);
helper(node->right, sum - node->val, out, res);
out.pop_back();
}
};
Notice helper
function is invoked twice in its inner function body.
So to sum up my questions:
- the Python function
helper
doesn't appear to be a Boolean type. How can it can be used withor
keyword? - Will
or
cause thehelper
function to be short-circuited thus resulting a different behavior as C++ version does. If not, how can it be?