Sword finger offer: Binary tree neutralization is a worthy path

Title description

Enter the root node and an integer of a binary tree, and print out all paths where the sum of the node values ​​in the binary tree is the input integer. The path is defined as a path starting from the root node of the tree and going down to the leaf node. (Note: In the list of return values, the array with the largest array length is at the top)
 
Idea: Because the problem is to output a return value that conforms to an integer, it must involve tree traversal. Here is the sum of the path from the root node to each node, so think about DFS
The algorithm comes, each recursion only needs to determine whether the current target value is zero and whether the left and right subtrees are all empty (leaf nodes), if it is satisfied, add the array, recursion
When the last child node is not satisfied, then pop_back, of course, it is possible that the current node value has been satisfied when it is not a leaf node, and at this time, if the condition is not satisfied, continue
Continue recursively to the leaf node, and then the target can only be added to the array if it meets the target.
 
Code:
/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    vector<vector<int>> res;
    vector<int> path;
    void find(TreeNode* root, int sum){
        if(root == nullptr) return;
        path.push_back(root -> val);
        sum -= root -> val;
        if(sum == 0 && !root -> left && !root->right) res.push_back(path);
        else{
            if(root -> left) find(root -> left, sum);
            if(root -> right) find(root -> right, sum);
        }
        path.pop_back();
    }
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        find(root, expectNumber);
        return res;
    }
};

 

Guess you like

Origin www.cnblogs.com/BillowJ/p/12730235.html