原题传送门—>>


Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

不就是深搜嘛。
但第一次还真没想清楚

WA代码共赏:

class Solution {
public:
    vector<int> tmp;
    vector<vector<int>> ans;
    int counter = 0;
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        if(!root)
            return ans;
        travel(root,sum);
        return ans;
    }
    int travel(TreeNode* node, int num)
    {
        if(!num && !node)//应当判别叶节点作为终点,而非空结点
        {
            if((++counter)%2)
            ans.push_back(tmp);
            return 0;
        }
        if(!node)
            return 0;
        tmp.push_back(node->val);
        travel(node->left, num - node->val);
        travel(node->right, num - node->val);
        tmp.pop_back();
        return 0;
    }

};

问题如注释所说。有空子树的未必是叶节点。
并且将判定空结点改为判定叶节点,省去了那个尴尬的计数器counter

AC代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> tmp;
    vector<vector<int>> ans;
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        if(!root)
            return ans;
        travel(root,sum);
        return ans;
    }
    int travel(TreeNode* node, int num)
    {
        if(!node)
            return 0;
        if(!node->left && !node->right)
        {
            if(!(num - node->val))
            {
                tmp.push_back(node->val);
                ans.push_back(tmp);
                tmp.pop_back();
            }
            return 0;
        }

        tmp.push_back(node->val);
        travel(node->left, num - node->val);
        travel(node->right, num - node->val);
        tmp.pop_back();
        return 0;
    }

};