Path Sum II

2019-05-25 22:58:26 浏览数 (1)

1. Description

2. Solution

2.1 Recursive

  • Version 1
代码语言:javascript复制
/**
 * 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<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> result;
        if(!root) {
            return result;
        }   
        vector<int> path;
        tranverseTree(root, sum, result, path);
        return result;
    }

     void tranverseTree(TreeNode* root, int sum, vector<vector<int>>& result, vector<int> path) {
        path.push_back(root->val);
        if(root->val == sum && root->left == NULL && root->right == NULL) {
            result.push_back(path);
        }
        if(root->left) {
            tranverseTree(root->left, sum - root->val, result, path);
        }
        if(root->right) {
            tranverseTree(root->right, sum - root->val, result, path);
        }
    }
};
  • Version 2
代码语言:javascript复制
/**
 * 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<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> result;
        if(!root) {
            return result;
        }   
        vector<int> path;
        tranverseTree(root, sum, result, path);
        return result;
    }

     void tranverseTree(TreeNode* root, int sum, vector<vector<int>>& result, vector<int>& path) {
        path.push_back(root->val);
        if(root->val == sum && root->left == NULL && root->right == NULL) {
            result.push_back(path);
            path.pop_back();
            return;
        }
        if(root->left) {
            tranverseTree(root->left, sum - root->val, result, path);
        }
        if(root->right) {
            tranverseTree(root->right, sum - root->val, result, path);
        }
        path.pop_back();
    }
};

0 人点赞