剑指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 ;
        
    }
};

 

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