[leetcode]Path Sum II

来源:互联网 发布:怎么看10月经济数据 编辑:程序博客网 时间:2024/06/03 16:08

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

DFS,当搜索到叶子节点时把路径存储下来。

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool ans = false;    vector<int> st;    vector<vector<int>> v;    vector<vector<int> > pathSum(TreeNode *root, int sum) {        if(root == NULL) return v;        st.push_back(root->val);        if(root->left == NULL && root->right == NULL){            int a = 0;            for(int i=0;i<st.size();i++){                a += st[i];            }            ans = (a==sum);            if(ans){            vector<int> ve;            for(int i=0;i<st.size();i++){                ve.push_back(st[i]);            }            v.push_back(ve);            }            return v;        }        pathSum(root->left,sum);        if(root->left != NULL) st.erase(st.end()-1);        pathSum(root->right,sum);        if(root->right != NULL) st.erase(st.end()-1);        return v;    }};
0 0
原创粉丝点击