Path Sum
来源:互联网 发布:高清喷码机软件 编辑:程序博客网 时间:2024/05/16 19:11
path-sum
Given the below binary tree and
递归代码:
递归:
如果使用递归,需要明确递归的结束条件,结束条件分为几类。递归的模式为:
Type f(...) {
if 满足结束条件1
return x;
if 满足结束条件2
return x;
......
递归表达式
}
if 满足结束条件1
return x;
if 满足结束条件2
return x;
......
递归表达式
}
---------------------------------------------------------------------------------------------------
题目:
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.
树的结构
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
* Definition for binary tree
* 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) {
return false;
}
if (!root->left && !root->right) {
return root->val == sum;
}
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
};
public:
bool hasPathSum(TreeNode *root, int sum) {
if (!root) {
return false;
}
if (!root->left && !root->right) {
return root->val == sum;
}
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
};
迭代代码:
由于先序、中序遍历栈中不会保留路径上的节点,只有后序遍历可以做到,因此使用迭代的方式应当使用后序遍历。
<参考:二叉树的遍历>
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
stack<TreeNode *> s;
TreeNode *pre = NULL, *cur = root;
int SUM = 0;
while (cur || !s.empty()) {
while (cur) {
s.push(cur);
SUM += cur->val;
cur = cur->left;
}
cur = s.top();
if (cur->right && pre != cur->right) {
cur = cur->right;
} else {
pre = cur;
s.pop();
SUM -= cur->val;
cur = NULL;
}
}
return false;
}
};
public:
bool hasPathSum(TreeNode *root, int sum) {
stack<TreeNode *> s;
TreeNode *pre = NULL, *cur = root;
int SUM = 0;
while (cur || !s.empty()) {
while (cur) {
s.push(cur);
SUM += cur->val;
cur = cur->left;
}
cur = s.top();
if (cur->left == NULL && cur->right == NULL && SUM == sum) {
return true;
}
}
cur = cur->right;
} else {
pre = cur;
s.pop();
SUM -= cur->val;
cur = NULL;
}
}
return false;
}
};
优化:
1、遍历到某个节点,此时和已经大于sum,则不再向下遍历。X,因为sum本身可取负值。
0 0
- Path Sum && Path Sum ||
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- 如果我闭上眼睛就是天黑
- 阻塞和非阻塞
- 在AIX操作系统中如何查看DS4000盘阵LUN状态?
- HDUJ 1072 Nightmare 搜索
- OU 库存组织和子库存关系
- Path Sum
- 数的划分
- hadoop+zookeeper+hbase分布式环境配置之zookeeper分布式环境搭建
- HDU 2016 数据的交换输出
- java 数字金额转大写金额
- Ant之build.xml详解
- java 过滤器实现
- JAVA 后台拼接分页查询SQL oracle/sqlserver/db2/达梦数据库通用
- 打印linx 中的environ变量