113. Path Sum II 路徑和 ||

題目鏈接
tag:

  • Medium;

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

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,



Return:
[
[5,4,11,2],
[5,8,4,5]
]

思路:
??用深度優(yōu)先搜索DFS,每當DFS搜索到新節(jié)點時,都要保存該節(jié)點。而且每當找出一條路徑之后,都將這個保存為一維vector的路徑保存到最終結(jié)果二位vector中。并且,每當DFS搜索到子節(jié)點,發(fā)現(xiàn)不是路徑和時,返回上一個結(jié)點時,需要把該節(jié)點從一維vector中移除。代碼如下:

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

類似題目:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 目錄 簡書的 markdown 都不支持 [TOC] 語法……我就不貼目錄了。下面按照類別,列出了29道關(guān)于二叉樹...
    被稱為L的男人閱讀 3,435評論 0 8
  • 題目 Given a binary tree and a sum, find all root-to-leaf p...
    時光雜貨店閱讀 171評論 0 0
  • Validate Binary Search Tree Same Tree (基礎(chǔ)) 101.symmetric ...
    lifesmily閱讀 357評論 0 0
  • 總結(jié)類型: 完全子樹(#222) BST(左右子樹值的性質(zhì),注意不僅要滿足parent-child relatio...
    __小赤佬__閱讀 764評論 0 0
  • 無意中翻到王朔的小說《我是你爸爸》,覺得還是有點意思的,書中的倆父子老馬和小馬還是挺逗的。 可愛的老馬 老馬(馬林...
    成都老王閱讀 1,840評論 0 3

友情鏈接更多精彩內(nèi)容