The sword refers to Offer_Programming questions_24

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.
/*
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> > FindPath(TreeNode* root,int expectNumber) {
        if(root == NULL){
            return vt;
        }
        num += root->val;
        path.push_back(root->val);
        if(num == expectNumber && root->left == NULL && root->right == NULL){
            vt.push_back(path);
        }
        if(num < expectNumber && root->left!=NULL){
            FindPath(root->left,expectNumber);
        }
        if(num < expectNumber && root->right!=NULL){
            FindPath(root->right,expectNumber);
        }
        num -= root->val;
        path.pop_back();
        return vt;
    }
private:
    vector<vector<int>> vt;
    vector<int> path;
    int num = 0;
};

  

Guess you like

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