[Sword finger offer] _10 Binary tree sum is a certain path value

Title description

Enter the heel 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.

Problem-solving ideas

If the sum of a path is required, then the inevitable termination condition is the leaf node. Starting from the root node, from left to right, the sum of each path is compared with the given value, which can be naturally found.
But often the problem of binary trees will use recursion, which is itself a binary tree, then the subtree must be a binary tree, if you find the law? ?
We can think of it this way, recursive once, the old call system stack saves data once. Since the sum of all nodes on the path is equal to the given value, it means that the sum of the given value minus the path is equal to 0 . It is not difficult to think that every time the value of the current root node is subtracted recursively, up to the leaf node, if the last value is equal to the value of the leaf node, then this problem can be solved .
We have to consider the special case, if the binary tree has only one node, and it happens that the value of that node is equal to the given value? ? Therefore, before subtracting the value of the current root node every time, first determine whether they are equal, and then subtract .
If the leaf nodes are not equal, then go up and then go to the right .
With the above ideas, it is not difficult to write the following code

Code

class Solution {
    vector<vector<int>> result;
    vector<int>  path;
public:
    void find(TreeNode* root,int expectnum)
    {
        if(root == NULL)
            return ;
        path.push_back(root->val);
        if(!root->left&&!root->right&& expectnum == root->val)
            result.push_back(path);
        else
        {
            if(root->left)
                find(root->left,expectnum-root->val);
            if(root->right)
                find(root->right,expectnum-root->val);
        }
        path.pop_back();
    }
    
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        find(root,expectNumber);
        return result;
    }
};
Published 253 original articles · praised 41 · 40,000+ views

Guess you like

Origin blog.csdn.net/liuyuchen282828/article/details/103767558