给定一棵二叉树和一个整型,判断是否存在一条从根节点到叶节点之和为给定整型的一条路径
前序递归:每次检查是否到达叶节点,如果是节点,检查此时的target是否等于该节点的值,若相等返回true,不相等返回false;递归检查左右子树,记得要把target 更新为减去此时节点值之后的值
bool hasPath(TreeNode* root, int target)
{
if(root == NULL)
return false;
if(root->left == NULL && root->right == NULL)
{
if(root->val == target)
return true;
else
return false;
}
return hasPath(root->left, target-root->val)
|| hasPath(root->right, target-root->val);
}
给定二叉树和一个整型,找到这棵树中所有路径和为该整型的路径
vector<vector<int>> hasPath(TreeNode* root, int target)
{
vector<vector<int>> all_path;
if(root == NULL)
return all_path;
vector<int> one_path;
int current_sum = 0;
hasPathHelper(root, target, all_path, one_path, current_sum);
return all_path;
}
void hasPathHelper(TreeNode* root, int target,
vector<vector<int>>& all_path,
vector<int>& one_path,
int current_sum)
{
one_path.push_back(root);
current_sum += root->val;
// 先序过程
if(root->left == NULL && root->right == NULL && current_sum == target)
{
all_path.push_back(one_path);
}
if(root->left)
hasPathHelper(root->left, target, all_path, one_path, current_sum);
if(root->right)
hasPathHelper(root->right, target, all_path, one_path, current_sum);
// 回溯,弹出当前节点
TreeNode* last = one_path.back();
current_sum -= last->val;
one_path.pop_back();
}
网友评论