标签:
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.
For example: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.
Tree Depth-first Search
这道题需要查找出是否有路径等于给定值,采用深度优先搜索的方法,在每次往下搜索时,记录下到当前结点的路径,然后若到了叶节点时
就判断下是否与之相等,再将判断的结果回溯就可以了:
#include<iostream>
#include<stack>
#include<set>
using namespace std;
// Definition for binary tree
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool ifsum(TreeNode* root,int sum,int cursum)
{
if(root==NULL)
return false;
if(root->left==NULL&&root->right==NULL)
return cursum+root->val==sum;
if(root->left!=NULL||root->right!=NULL)
return ifsum(root->left,sum,cursum+root->val)||ifsum(root->right,sum,cursum+root->val);
}
bool hasPathSum(TreeNode *root, int sum) {
return ifsum(root,sum,0);
}
int main()
{
}
还看到有一种基本与上面类似的方法,只是将当前的路径放在了外面作为迁居变量,而这里需要注意的是,在每次向下搜索完了之后,要记得在之前加了当前结点值的要减掉这个值
#include<iostream>
#include<stack>
#include<set>
using namespace std;
// Definition for binary tree
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int sum_temp;
int targetsum;
bool ifsum(TreeNode* root)
{
if(root==NULL)
return false;
if(root->left==NULL&&root->right==NULL)
return targetsum+root->val==sum_temp;
targetsum+=root->val;
bool res1=ifsum(root->left);
bool res2=ifsum(root->right);
targetsum-=root->val;//这里由于是全局变量,所以在前面加了之后,在这个结点算完后,要减掉
return res1||res2;
}
bool hasPathSum(TreeNode *root, int sum) {
sum_temp=sum;
targetsum=0;
return ifsum(root);
}
int main()
{
}
leetcode_112题——Path Sum(二叉树,深度优先搜索)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4452868.html