Path Sum II

来源:互联网 发布:淘宝显示在线人数插件 编辑:程序博客网 时间:2024/05/22 09:00

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

For 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]]

和上题类似,只是要遍历各种情况, 考虑到inorder的traverse,只需要push,然后遍历左右后pop就可以只维护一个vector, O(n)的空间, O(lgn)的效率,不过因为是递归,所以stack上还有空间。


/** * Definition for binary tree * 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> > res;        vector<int> path;        helper(root, sum, path, res);        return res;    }        void helper(TreeNode* root, int sum, vector<int>& path, vector<vector<int> > & res){        if (root==0)            return;        path.push_back(root->val);        if (!root->left && !root->right && root->val==sum){            res.push_back(path);        }        helper(root->left, sum-root->val, path,res);        helper(root->right,sum-root->val, path,res);        path.pop_back();    }};




0 0