Niuke.com brush questions | The path that sums to a certain value in the binary tree

Topic source: Niuke.com

programming connection

Topic description

Input a binary tree and an integer, print out all paths in the binary tree whose sum of node values ​​is the input integer. A path is defined as a path from the root node of the tree down to the nodes passed by the leaf nodes.

Parse:

Classic DFS algorithm, depth-first algorithm

class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        vector<vector<int>>ret;
        vector<int>path;
        dfs(ret,root,path,expectNumber,0,0);
        return ret;
    }

    void dfs(vector<vector<int>>&ret,TreeNode* root,vector<int>&path,int expectNumber,int len,int sum)
    {
        if(root == nullptr)
            return;
        if(len == path.size())
            path.push_back(root->val);
        else
            path[len] = root->val;

        if(sum + root->val == expectNumber && root->left == nullptr && root->right == nullptr)
        {
            vector<int>arr(len+1);
            for(int i=0;i<len+1;i++)
            {
                arr[i] = path[i];
            }
            ret.push_back(arr);
        }

        dfs(ret,root->left,path,expectNumber,len+1,sum + root->val);
        dfs(ret,root->right,path,expectNumber,len+1,sum + root->val);       
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325602498&siteId=291194637