NowCoder
题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
解题思路
1 DFS递归大法
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector< vector<int>> res;
vector<int> trace;
if(root) dfs(root, expectNumber, res, trace);
return res;
}
void dfs(TreeNode* root, int en, vector< vector<int>> &res, vector<int> &trace) {
trace.push_back(root->val);
if(en == root->val && !root->left && !root->right) res.push_back(trace);
if(root->left) dfs(root->left, en-root->val, res, trace);
if(root->right) dfs(root->right, en-root->val, res, trace);
trace.pop_back();
}
};
2 带buffer的递归大法
class Solution {
public:
vector<vector<int> > buffer;
vector<int> tmp;
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if(root == NULL) return buffer;
tmp.push_back(root->val);
int nextnum = expectNumber - root->val;
if(nextnum == 0 && root->left == NULL && root->right == NULL) buffer.push_back(tmp);
FindPath(root->left, nextnum);
FindPath(root->right, nextnum);
if(tmp.size()!=0) tmp.pop_back();
return buffer;
}
};
相关问题
判断二叉树路径和是否等于一个数: leetcode 112
Given the below binary tree and
sum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path
5->4->11->2
which sum is 22.
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(!root) return false;
if(!root->left && !root->right && root->val == sum) return true;
return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
}
};
统计二叉树路径和等于一个数的路径数量:leetcode 437
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11
class Solution {
public:
void pathSumHelper(TreeNode *root, int sum , vector<int> ¤tPath, int &pathCount) {
if(!root) return;
currentPath.push_back(root->val);
int currentSum = 0;
for(int j=currentPath.size()-1; j>=0; j--) {
currentSum += currentPath[j];
if(currentSum == sum) pathCount++;
}
pathSumHelper(root->left, sum, currentPath, pathCount);
pathSumHelper(root->right, sum, currentPath, pathCount);
currentPath.pop_back();
}
int pathSum(TreeNode* root, int sum) {
int pathCount = 0;
vector<int> currentPath;
pathSumHelper(root, sum, currentPath, pathCount);
return pathCount;
}
};