[LeetCode] Sword refers to Offer 34. The path where the sum is a certain value in the binary tree (medium) dfs backtracking

Sword refers to Offer 34. Paths whose sum is a certain value in
a binary tree Input a binary tree and an integer, and print out all paths where the sum of node values ​​in the binary tree is the input integer. Starting from the root node of the tree and going down to the nodes passed by the leaf nodes form a path.

示例:
给定如下二叉树,以及目标和 sum = 22

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
返回:

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

Code:

/**
 * 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>> ans; //答案
    vector<int> t; //过程

    void dfs(int s,TreeNode* root, int sum)
    {
    
    
        if(root->left==NULL && root->right==NULL) //叶子
        {
    
    
            if(s==sum) //和为sum
            {
    
    
                ans.push_back(t);
                return;
            }
        }

        if(root->left) //左树存在
        {
    
    
            t.push_back(root->left->val);
            dfs(s+root->left->val,root->left,sum); //累加左树的值
            t.pop_back(); //回溯
        }

        if(root->right) //右树存在
        {
    
    
            t.push_back(root->right->val);
            dfs(s+root->right->val,root->right,sum); //累加右树的值
            t.pop_back(); //回溯
        }

    }

    vector<vector<int>> pathSum(TreeNode* root, int sum) {
    
    
        if(root==NULL) return ans; //树为空
        t.push_back(root->val); //先加入根的值
        dfs(root->val,root,sum); 
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45260385/article/details/108477114