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. 头文件limits—各个类型的数据的范围

    要想知道各个类型的数据如int.float.double.long等所能表示的范围,可以加上头文件<limits>,这些类型的范围都在类numeric_limits中定义了的. 类模板:t ...

  2. Ubuntu14.04上安装openGL

    安装命令:sudo apt-get install build-essential sudo apt-get install libgl1-mesa-dev sudo apt-get install ...

  3. LinkedHashSet的概述和使用

    LinkedHashSet的特点: 可以保证怎么存就怎么取 package online.msym.set; import java.util.LinkedHashSet; public class ...

  4. 微信小程序-开发入门

    微信小程序已经火了一段时间了,之前一直也在关注,就这半年的发展来看,相对原生APP大部分公司还是不愿意将主营业务放到微信平台上,以免受制于腾讯,不过就小程序的应用场景(用完即走和二维码分发等)还是很值 ...

  5. 使用Struts2校验器

    今天遇到了这样的问题:我的jsp页面.web.xml.struts.xml.UserAction-validation.xml等内容写的都正确,就是无法使用校验器!在网上找了半天就是不出来,迫不得已我 ...

  6. Web移动端的常用组件库

    normalize http://necolas.github.io/normalize.css/ 最受欢迎的css reset 保留有用的默认值,这个区别于其他的CSS resets 标准化大范围的 ...

  7. python文件读写出现乱码总结

    1.错误的打开方式 #coding=utf-8f = open("test.txt",'w+')f.write('Mars is slim,isn\'he? \n 火星教')pri ...

  8. Android下使用busybox的ifconfig

    busybox ifconfig eth0 10.0.16.45 netmask 255.255.254.0 broadcast 10.0.16.186busybox route add defaul ...

  9. 20分钟快速了解Redis

    Redis可以说是目前最火爆的NoSQL数据库! 过去几年,Memcached很盛行,现在有很多公司已将Memcached替换成了Redis.当然,很多人替换并不清楚为什么,只是感觉不想让主流抛弃,这 ...

  10. 接口调用 GET方式

    /** * 第一步 视图展示 . 视图页面(忽略) * @return [type] [description] */ /** * 第二步 控制器先将要运行的接口处理好(接口及参数)传到到Model层 ...