Path Sum (leetcode)

来源:互联网 发布:软件编程自学网站 编辑:程序博客网 时间:2024/05/01 03:24

题目:

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:
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://oj.leetcode.com/problems/path-sum/

解题思路:用深搜,即可。

#include<iostream>#include<queue>using namespace std;struct TreeNode {    int val;    TreeNode *left;    TreeNode *right;    TreeNode(int x) : val(x), left(NULL), right(NULL) {}};bool dfs(TreeNode *root,int temp,int sum){if(root==NULL)return false;if(root->left==NULL && root->right==NULL){if(temp+root->val==sum)return true;else return false;}if(dfs(root->left,temp+root->val,sum))return true;if(dfs(root->right,temp+root->val,sum))return true;return false;} bool hasPathSum(TreeNode *root, int sum) {if(root==NULL && sum!=0)return 0;return dfs(root,0,sum); }int main(){TreeNode *root=new TreeNode(1);root->left=new TreeNode(2);root->right=new TreeNode(3);cout<<hasPathSum(root,5)<<endl;system("pause");return 0;}

0 0
原创粉丝点击