my js and c++ solution.


  • 0
    N
    js:
    var pathSum = function(root, sum) {
        var ans = new Array(), st = new Array();
        function solve(rt, curSum){
            if(rt == null)return;
            st.push(rt.val);
            curSum += rt.val;
            if(rt.left == null && rt.right == null && curSum == sum){
                ans[ans.length] = new Array();
                for(var i = 0; i < st.length; i++)ans[ans.length - 1].push(st[i]);
            }
            if(rt.left != null)solve(rt.left, curSum);
            if(rt.right != null)solve(rt.right, curSum);
            st.pop();
        };
        solve(root, 0);
        return ans;
    };
    
    
    c++:
    class Solution {
    public:
        vector<int>st;
        vector<vector<int> > ans;
        int s;
        vector<vector<int> > pathSum(TreeNode* root, int sum) {
            st.clear();
            ans.clear();
            s = sum;
            solve(root, 0);
            return ans;
        }
        void solve(TreeNode* root, int curSum){
            if(root == NULL)return;
            curSum += root->val;
            st.push_back(root->val);
            if(root->left == NULL && root->right == NULL && curSum == s){
                ans.push_back(vector<int>());
                for(int i = 0; i < st.size(); i++){
                    ans.back().push_back(st[i]);
                }
            }
            if(root->left != NULL)solve(root->left, curSum);
            if(root->right != NULL)solve(root->right, curSum);
            st.pop_back();
        }
    };
    

Log in to reply
 

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