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的更多相关文章

  1. 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 ...

  2. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  3. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  4. [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. ...

  5. [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 ...

  6. [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 ...

  7. 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 ...

  8. Path Sum

    需如下树节点求和 5  /  \ 4     8  /     /  \ 11  13    4 / \     /  \  7    2      5   1 JavaScript实现 window ...

  9. [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 ...

  10. [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 ...

随机推荐

  1. 解决MVC中JsonResult返回 弹出文件下载对话框

    设置一下返回类型为HTML TEXT就可以了 JsonResult json = Json(xxx, JsonRequestBehavior.DenyGet); json.ContentType = ...

  2. SQLServer 数据库不能重命名的解决方案

    无法用排他锁锁定该数据库,以执行该操作 SQL Server2008 因为可能其他用户在占用着该数据库 解决办法为 把数据库先改为单用户的,再改数据库名,再改回多用户的 USE [master] GO ...

  3. iOS开发之自定义UITableView的cell

    系统默认的UITableViewCell的每行都有横线(分隔符),就算没有数据也是如此,有时候我们想只在有数据的地方有下划线,可以去除下划线,然后在awarkFromNid方法中使用addsubvie ...

  4. trimpath javascript的学习

    TrimPath是javascript模板引擎. 这几天有一个项目涉及到trimpath这个框架,所以就花了一点时间研究了一下,这个框架和别的javascript框架不太一样的地方就是模板的概念,就是 ...

  5. mysq常用l性能分析方法

    orzdba查看读写./orzdba.pl --mysql -S /data/mysql30001/mysql.sock 语句查看读写命令数量,以及数据库TPS,传输的大小 查看processlist ...

  6. 用js实现图片的无缝滚动效果

    实现图片的无缝滚动就是要让你的图片集在一定时间里自动切换,那就需要js里的定时器来控制时间. js中关于定时器的方法有两种:setTimeout和setInterval.它们接收的参数是一样的,第一个 ...

  7. SpringMVC参数校验(针对`@RequestBody`返回`400`)

    SpringMVC参数校验(针对@RequestBody返回400) 前言 习惯别人帮忙做事的结果是自己不会做事了.一直以来,spring帮我解决了程序运行中的各种问题,我只要关心我的业务逻辑,设计好 ...

  8. dotweb——go语言的一个微型web框架(二)启动dotweb

    以上的代码截图表示启动一个dotweb服务,在浏览器里输入127.0.0.1:8080,将会得到一个"index"的页面. app := dotweb.New() dotweb.N ...

  9. 解决Appium 抓取toast

    首先我们先看看这个gif,图中需要,要抓取的字符串--->请输入转让份数 1.要导入java-client-5.0.0-SNAPSHOT.jar 包的地址:链接:http://pan.baidu ...

  10. Redis简单几步

    第一步redis安装:1.首先确认下载包为64位的还是32位的2.下载http://code.google.com/p/servicestack/downloads3.解压下载包得到以下文件:cygw ...