0

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:

  1. the Python function helper doesn't appear to be a Boolean type. How can it can be used with or keyword?
  2. Will or cause the helper function to be short-circuited thus resulting a different behavior as C++ version does. If not, how can it be?
JP Zhang
  • 767
  • 1
  • 7
  • 27
  • 1
    For example, `(0 or "hello") == "hello"`, `([5] or 4) == [5]` – ForceBru Oct 02 '19 at 15:38
  • 1
    Note that `bool(None) == False`. If the function returns `None` it evaluates to boolean `False`. – berkelem Oct 02 '19 at 16:01
  • 1. The result is always `None`, which is treated as `False`. 2. Yes, but it never short circuits, `or` short circuits for `True`. – Caleth Oct 02 '19 at 16:01
  • 1
    I'd reject `return self.helper(root.left, target - root.val, res, temp+[root.val]) or self.helper(root.right, target - root.val, res, temp+[root.val])` and ask for `self.helper(root.left, target - root.val, res, temp+[root.val])` newline `self.helper(root.right, target - root.val, res, temp+[root.val])` – Caleth Oct 02 '19 at 16:07

0 Answers0