[LeetCode]Path Sum
来源:互联网 发布:数据如何做韦恩图 编辑:程序博客网 时间:2024/05/29 15:02
思路:
深度搜索(这里采用 回溯法)
1,先决条件:找到树根
2,不变式:遍历子node,传递sum和当前和 curSum
3,结束条件:node没有子节点,判断sum 是否等于curSum
4,临界条件:树为空
很简单,一遍过。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool hasPathSum(TreeNode* root, int sum) { if (root == NULL){ return false; } return bfs(root, sum, 0); } bool bfs(TreeNode* node, int sum, int curSum){ if(node->left == NULL && node->right == NULL){ return sum == (curSum + node->val); }else{ if (node->left != NULL){ if ( bfs(node->left, sum, curSum + node->val) ){ return true; } } if (node->right != NULL){ if ( bfs(node->right, sum, curSum + node->val) ){ return true; } } } }};
0 0
- [LeetCode]Path Sum
- [LeetCode]Path Sum II
- leetcode Path Sum && Path Sum ||
- 【Leetcode】Path Sum (Sum)
- leetcode:leetcode :Path Sum
- 【Leetcode】Path Sum II (Sum)
- LeetCode: Minimum Path Sum
- LeetCode: Path Sum
- LeetCode: Path Sum II
- LeetCode Minimum Path Sum
- LeetCode Path Sum
- LeetCode Path Sum II
- [Leetcode] Path Sum
- [Leetcode] Path Sum II
- LeetCode : Minimum Path Sum
- [Leetcode] Minimum Path Sum
- LeetCode: Path Sum
- LeetCode: Path Sum II
- jeecg项目源码maven工程搭建
- 大数据的经济效益
- 题目1196:成绩排序
- Java事件处理
- 编写一个C++风格的程序,计算输出Fibonacci数列的前20项
- [LeetCode]Path Sum
- subversion check out时报错 Can't read from connection 远程主机强迫关闭了一个现有的连接
- [POJ2417]Discrete Logging
- json 总结
- C---测试程序1
- 初次了解存储过程和存储函数和触发器的例子
- 启动安卓模拟器时出现 The connection to adb is down, and a severe error has occured
- J2SE之基本数据类型及转换
- SVN历史版本删除 瘦身svn库