Title Description
Input the root node of a binary tree and an integer, and print out all paths in the binary tree whose sum of node values is the input integer in lexicographical order. A path is defined as a path from the root node of the tree down to the nodes passed by the leaf nodes.
Solution: If the problem of inputting an integer is not considered, it is a problem of printing the path of the binary tree. Printing the binary tree is nothing more than traversing the tree; adding a path equal to a certain integer can be filtered with a few changes. The specific program is implemented as follows. The code is based on Written in my own mind, it may be a bit redundant.
/*
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) {
vector<vector<int>> result;
if(root == NULL)
return result;
vector<int> path;
path.push_back(root -> val);
int sum = root -> val;
DFS(root,expectNumber,result,path,sum);
return result;
}
void DFS(TreeNode *root,int expectNumber,vector<vector<int>> &result, vector<int> path,int sum)
{
if(root -> left == NULL && root -> right == NULL && sum == expectNumber)
{
result.push_back(path);
return;
}
if(root -> left == NULL && root -> right == NULL && sum != expectNumber)
return;
int sum1 = sum;
vector<int> path1 = path;
if(root -> left != NULL)
{
sum += root -> left -> val;
path.push_back(root -> left -> val);
DFS(root -> left,expectNumber,result,path,sum);
}
if(root -> right != NULL)
{
sum1 += root -> right -> val;
path1.push_back(root -> right -> val);
DFS(root -> right,expectNumber,result,path1,sum1);
}
}
};