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. 开源的.NET定时任务组件Hangfire解析

    项目慢慢就要开工了,很多园友都在问这个事情,看来大伙对这事很上心啊,事情需要一步步的来,尽量写出一个我们都满意的项目.以前每次在博客前面都会扯淡一下,不过很多人都抱怨这样做不好,加上我这人扯淡起来就停 ...

  2. Unity文档总结(2)-Understanding Automatic Memory Management

    当一个对象.字符串.数组被创建的时候,从中间池申请分配需要存储的内存称为堆.当该部分不在使用时,一度占用的内存被释放收回,用于别的事物.在过去,它通常由开发人员分配和释放这些堆内存块,明确相应的功能调 ...

  3. mybatis的学习笔记

    前几天学习了mybatis,今天来复习一下它的内容. mybatis是一个基于Java的持久层框架,那就涉及到数据库的操作.首先来提出第一个问题:java有jdbc连接数据库,我们为什么还要使用框架呢 ...

  4. Android 增加(键盘)按键

    以添加 camera按键为例(红色是需要添加的) 一.kernel键值定义 (1)键扫描码 ScanCode是由linux的Input驱动框架定义的整数类型,可参考input.h头文件,即geteve ...

  5. CSS.05 -- 规避脱标 定位的盒子居中、CSS标签规范、溢出隐藏、内容移除(网页优化)、CSS精灵图

    规避脱标   定位的盒子居中显示 Margin:0 auto : 只能让标准流的盒子居中对齐 当A是B的父系,B可以使用 margin-left:auto: 来获得相当于定位right:0:的效果 M ...

  6. virtualenv 安装不同版本的虚拟环境的办法

    废话不多说直接上代码 virtualenv -p C:\Python27\python2.exe env 上面的*.exe是你要使用的python版本的exe文件的绝对路径. 官方文档参考:http: ...

  7. python try/except/finally

    稍微总结一下,否则总是忘. [python] view plaincopyprint? x = 'abc' def fetcher(obj, index): return obj[index] fet ...

  8. WebApi client 的面向切面编程

    .Net的面向切面编程 .Net的服务端应用AOP很常见,在Asp.net MVC与Asp.net WebApi等新框架里到处都有AOP的影子,我们可以把一个服务方法“切”为很多面,日志面.验证面.请 ...

  9. Java并发基础:进程和线程之由来

    转载自:http://www.cnblogs.com/dolphin0520/p/3910667.html 在前面,已经介绍了Java的基础知识,现在我们来讨论一点稍微难一点的问题:Java并发编程. ...

  10. C++11 新特性总结

    前言 转载请注明出处,感谢! C++11 的新特性 1 变量和基本类型 1.1 long long 类型 扩展精度浮点数,10位有效数字 1.2 列表初始化 初始化的几种不同形式,其中用花括号来初始化 ...