LeetCode | Path Sum II

来源:互联网 发布:大众点评数据 编辑:程序博客网 时间:2024/06/10 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]
]

需要找出每一个节点的位置,所以需要保留所有遍历的结果。
这就很尴尬了,我一开始想的是开多个数组
描述
但是这样的结果是可怕的,因为数组的大小会越来越大,而且会引用到无用数组。
最重要的一点是,每次到达一个新的节点,将不知道使用之前哪一个数组。

正确的方法应当是仅仅使用一个数组,但是这个数组实现了类似栈的功能(DFS)
一直只需要一个cur数组,然后递归过后使用cur.pop_back()
神器啊这个函数,它可以弹出数组最后一个元素,这样就可以像栈一样操作。

最重要的是,这一个数组可以衍生出多个数组,主要还归功于vector.pus_back()
它可以生成当前对象的拷贝,然后再放入vector中,牛…

class Solution {public:    vector<vector<int>> pathSum(TreeNode* root, int sum) {        vector<vector<int>> result;        if(!root) return result;        vector<int> cur;        pathSumArr(root,sum,cur,result);        return result;    }    void pathSumArr(TreeNode* root,int sum,vector<int> &cur,vector<vector<int>>& result){        if(!root) return;        cur.push_back(root->val);        if(sum==root->val && !root->left && !root->right){            result.push_back(cur);        }        pathSumArr(root->left,sum-root->val,cur,result);        pathSumArr(root->right,sum-root->val,cur,result);        //此句神作...        cur.pop_back();    }};
0 0
原创粉丝点击