Niuke.com’s sword refers to Offer – a path that sums to a certain value in a binary tree

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.

Problem solving ideas

This problem can be solved by recursive method. Every time we visit a node, we judge the node: if the node is a leaf node (the left and right subtrees are empty), and the value is equal to the required value, then the The value of the node is stored in the path, and the path is stored; if the node does not meet the conditions, it continues to recursively visit its child nodes. When the visit is over, the recursive function will automatically return to its parent node. So we need to delete the current node on the path before the function exits to ensure that the path is exactly the path from the root node to the parent node when returning to the parent node .

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>> FindPath(TreeNode* root,int expectNumber) {
        if( root == NULL )
            return res;
        vector<int> temp_res;
        help(temp_res, root, expectNumber);
        return res;
    }
    vector<vector<int>> res;
    void help(vector<int> temp_res, TreeNode* node,int num)
    {
        if( node->left == NULL && node->right == NULL && node->val == num )
        {
            temp_res.push_back(node->val);
            res.push_back(temp_res);
            return;
        }
        temp_res.push_back( node->val );
        if( node->left != NULL )
            help(temp_res, node->left, num-node->val );
        if( node->right != NULL )
            help(temp_res, node->right, num-node->val );
        return;
    }
};

Guess you like

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