[Question] P182 sword refers to offer: Interview question 34: The path where the sum of the binary tree is a certain value

Interview Question 34: Paths whose sum is a certain value in
a binary tree Enter a binary tree and a constant, and print out all paths whose node values ​​in the binary tree are the input integer.
Starting from the root node of the tree and going down to the leaf nodes, the nodes that pass through form a path.

Leetcode link: https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/submissions/

class Solution
{
    
    
public:
    vector<vector<int>> pathSum(TreeNode* root, int target)
    {
    
    
        vector<vector<int>> ans;
        if(root == NULL)
            return ans;
        vector<int> path;
        int sum = 0;
        FindPath(root, target, ans, path, sum);
        return ans;
    }

    void FindPath(TreeNode* root, int target, vector<vector<int>>& ans, vector<int>& path, int sum)
    {
    
    
        if(root == NULL)
            return;
        path.push_back(root->val);
        sum += root->val;

        bool isLeaf = (root->left == NULL && root->right == NULL);
        if(isLeaf && sum == target)
            ans.push_back(path);

        if(root->left)
            FindPath(root->left, target, ans, path, sum);
        if(root->right)
            FindPath(root->right, target, ans, path, sum);
        path.pop_back();
    }
};

In the previous code, we use the vector in the standard template library to implement a stack to save the path. Each time we use push_back to add nodes at the end of the path, and pop_back to delete nodes at the end of the path, so as to ensure the first entry of the stack. Later characteristics. The reason why the stack in STL is not used directly here is that only the top element of the stack can be obtained in the stack, and when we print the path, we need to get all the nodes on the path, so std::stack is not the best when the code is implemented. select.

Guess you like

Origin blog.csdn.net/m0_46613023/article/details/115033879