劍指offer-面試題 34:二叉樹中和爲某一值的路徑

題目描述:

輸入一棵二叉樹和一個整數,打印出二叉樹中結點值的和爲輸入整數的所有路徑。

從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。

樣例

給出二叉樹如下所示,並給出num=22。
      5
     / \
    4   6
   /   / \
  12  13  6
 /  \    / \
9    1  5   1

輸出:[[5,4,12,1],[5,6,6,5]]

算法:

DFS 

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章