1.题目描述
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
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.
来自 <https://leetcode.com/problems/path-sum/description/>
2.问题分析
判断二叉树是否存在一条到叶子结点的路径,该路径所经过的所有结点值的和等于给定的目标值。首先想到的应该是使用堆栈,结点入栈时,将该结点值累加到,结点出栈时 ,将该结点值减去,当访问到叶子结点时,判断该路径值是否和目标值一样。
3.C++代码
//我的代码:(55%)
bool hasPathSum(TreeNode* root, int sum)
{
TreeNode*p = root;
TreeNode*r = NULL;
stack<TreeNode*>s;
int sum_tmp=0;
while (!s.empty()||p!=NULL)
{
while (p != NULL)
{
s.push(p);//第一次访问
sum_tmp += p->val;
p = p->left;
}
p = s.top();
if (p->left == NULL&&p->right == NULL)
{
if (sum_tmp == sum)
return true;
}
if (p->right&&p->right != r)
{
p = p->right;
}
else
{
s.pop();
sum_tmp -= p->val;
r = p;
p = NULL;
}
}
return false;
}
//遍历二叉树:每个结点都会经过三次
void print_tree(TreeNode*root)
{
TreeNode*p = root;
TreeNode*r = NULL;
stack<TreeNode*>s;
while (!s.empty() || p != NULL)
{
while (p!=NULL)
{
s.push(p);
cout << p->val<<"," << endl;//第一次访问,并入栈
p = p->left;
}
p = s.top();
// if (p->right == NULL&&p->left == NULL)
// {
// cout << p->val << "," << endl;
// }
if (p->right&&p->right != r)
{
cout << p->val << "," << endl;//第二次访问,访问左子树后访问右子树前
p = p -> right;
}
else
{
s.pop();
cout << p->val << "," << endl;//第三次访问,并出栈
r = p;
p = NULL;
}
}
}
//递归的方法:
bool hasPathSum(TreeNode* p, int sum)
{
if (p == NULL)
return false;
if (p->left&&p->right)//左右结点都存在,则对左右子树进行递归
{
return hasPathSum(p->left, sum - p->val) || hasPathSum(p->right, sum - p->val);
}
else if (p->left)//仅有左子树存在,则对左子树进行递归
{
return hasPathSum(p->left, sum - p->val);
}
else if (p->right)//仅有右子树存在,则对右子树进行递归
{
return hasPathSum(p->right, sum - p->val);
}
else//叶子结点
return p->val == sum;
}