path sum i
Problem Statement:
Path sum i
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.
Solution one(traverse version):
This is the traverse version.
For each node:
- Check if it is NULL, yes, return false
- If it is not NULL
- Update the sum, sum = sum - node->val
if current node is leaf node( node->left == NULL && node->right == NULL) and the new sum is equal to 0, we find the answer, return true.
Not leaf node, node left child is not empty and there is a path in left child or right child is not empty and there is a path in right child, return true.
Otherwise, return false.
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL){
return false;
}
sum -= root->val;
if(sum == && root->left == NULL && root->right == NULL){
return true;
}
if((root->left && hasPathSum(root->left, sum)) || (root->right && hasPathSum(root->right, sum))){
return true;
}
return false;
}
};
Solution two(divide && conquer):
Divide the question to left and right, return true if there is one true between left and right.
otherwise, return false
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL){
return false;
}
sum -= root->val;
if(root->left == NULL && root->right == NULL && sum == ){
return true;
}
// divide
bool leftHasPathSum = hasPathSum(root->left, sum);
bool rightHasPathSum = hasPathSum(root->right, sum);
// conquer
if(leftHasPathSum || rightHasPathSum){
return true;
}
return false;
}
};
Solution three(while loop and preorder to solve the problem):
Since we need find a path from root to leaf, the sum is equal to a given value. We traverse the tree from root by preorder: root->left->right.
Current node is not empty:
- if it is a leaf and sum is already equal to 0, we find a path, return true.
- else go to the left child of current node.
Current node is empty:
- Pop the top element from stack and pop the sum value from value stack, this value corresponding to the sum from root to current node.
Until the stack is empty, we return false.
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL){
return false;
}
stack<TreeNode*> node_stack;
stack<int> val_stack;
node_stack.push(root);
val_stack.push(root->val);
TreeNode* cur_node;
int cur_val = ;
while(!node_stack.empty()){
if(root){
cur_val += root->val;
node_stack.push(root);
val_stack.push(cur_val);
if(root->left == NULL && root->right == NULL && cur_val == sum){
return true;
} else {
root = root->left;
}
} else {
root = node_stack.top();
node_stack.pop();
root = root->right;
cur_val = val_stack.top();
val_stack.pop();
}
}
return false;
}
};
NOTES:
The important for non-traverse version is the value stack, we need keep a value stack. Each time, we need push the sum value to stack when we push a node to stack.
we can not keep a variable to store the sum for current node. That does not work.
I know how to solve this problem, however, spend much time for configure out that to keep a stack.
path sum i的更多相关文章
- Leetcode 笔记 113 - Path Sum II
题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...
- Leetcode 笔记 112 - Path Sum
题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...
- [LeetCode] Path Sum III 二叉树的路径和之三
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- [LeetCode] Binary Tree Maximum Path Sum 求二叉树的最大路径和
Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. ...
- [LeetCode] Path Sum II 二叉树路径之和之二
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- [LeetCode] Path Sum 二叉树的路径和
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...
- Path Sum II
Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals ...
- Path Sum
需如下树节点求和 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 JavaScript实现 window ...
- [leetcode]Binary Tree Maximum Path Sum
Binary Tree Maximum Path Sum Given a binary tree, find the maximum path sum. The path may start and ...
- [leetcode]Path Sum II
Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals ...
随机推荐
- cuda编程学习2——add
cudaMalloc()分配的指针有使用限制,设备指针的使用限制总结如下: 1.可以将其传递给在设备上执行的函数 2.可以在设备代码中使用其进行内存的读写操作 3.可以将其传递给在主机上执行的函数 4 ...
- [AndroidTips]startService与bindService的区别
Service的生命周期方法比Activity少一些,只有onCreate, onStart, onDestroy我们有两种方式启动一个Service,他们对Service生命周期的影响是不一样的. ...
- 泛型加委托在EF下的操作例子
接下来放一个用SqlBulkCopy插入数据的例子,运用了泛型委托和反射.就当好好的运用这些知识. public static void AddEntityByBulk(IList entitys,s ...
- 老李分享:JDK,JRE,JVM区别与联系
poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工作为目标.如果对课程感兴趣,请大家咨询qq:908821478,咨询电话010-845052 ...
- QTP自动化测试培训:描述编程之WebElement
QTP自动化测试培训:描述编程之WebElement 通过描述性编程技术,来描述出来输入框: set po=browser("creationtime:=0").page(&q ...
- 老李分享:《Linux Shell脚本攻略》 要点(二)
老李分享:<Linux Shell脚本攻略> 要点(二) poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工作为目标.如果对课 ...
- Java中执行shell笔记
在java中执行shell有好几种方式:第一种(exec)方式一 public static synchronized void runshell2() { File superuser = n ...
- MySQL中文全文搜索
我们在mysql数据中可以使用match against语句解决中文全文搜索的问题 先看一个例句: SELECT * FROM v9_search WHERE `siteid`= '1' AND `t ...
- C# WebClient、jQuery ajax jsonp实现跨域
WebClient 无传输数据获取 Uri uri = new Uri(allURL); WebClient wc = new WebClient(); wc.Encoding = System.Te ...
- 跨web浏览器的IC卡读卡器解决方案
BS结构的程序,如果要与IC卡读卡器通信本身就是件不容易解决的事情.微软的activex ocx技术将这种应用限制在IE浏览器上了,不兼容其它的浏览器.而Chrome使用插件也不兼容IE和其他的浏览器 ...