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. empty 语句

    empty 语句: 用来表明没有语句, 尽管JavaScript语法希望有语句会被执行. empty语句 用分号表示 (;) ,用来指明没有语句会被执行, 尽管此时JavaScript语法需要执行语句 ...

  2. CSV工具类

    分享自己昨天写的CSV工具类, 主要实现解析CSV格式, 直接上代码 #region private /// <summary> /// 从sr当前位置解析一个栏位 /// </su ...

  3. Hive基础知识梳理

    Hive简介 Hive是什么 Hive是构建在Hadoop之上的数据仓库平台. Hive是一个SQL解析引擎,将SQL转译成MapReduce程序并在Hadoop上运行. Hive是HDFS的一个文件 ...

  4. 大数据学习记录之ssh绵密登录

    1,在服务器端 ssh-keygen 2,使用ssh-copy-id 192.168.2.146 3,再测试一下ssh 192.168.2.146 exit 退出当前登录 具体流程为:A,B两台机器 ...

  5. 老李推荐:第8章3节《MonkeyRunner源码剖析》MonkeyRunner启动运行过程-启动AndroidDebugBridge 3

    首先它通过查找JVM中的System Property来找到"com.android.monkeyrunner.bindir"这个属性的值,记得前面小节运行环境初始化的时候在mon ...

  6. JS中遍历语法的比较

    for循环 JavaScript 提供多种遍历语法.最原始的写法就是for循环.(假设myArray是数组,下面同理) let arr = [1,2,3,4,5]; for (var index = ...

  7. Influxdb1.2.2安装_Windows

    一.文件准备 1.1 文件名称 influxdb-1.2.2_windows_amd64.zip 1.2 下载地址 https://portal.influxdata.com/downloads [注 ...

  8. 在 redhat 6.4上安装Python 2.7.5

    在工作环境中使用的是python 2.7.*,但是CentOS 6.4中默认使用的python版本是2.6.6,故需要升级版本. 安装步骤如下: 1,先安装GCC,用如下命令yum install g ...

  9. asp.net core 编译mvc,routing,security源代码进行本地调试

    因为各种原因,需要查看asp.net core mvc的源代码来理解运行机制等等,虽说源代码查看已经能很好的理解了.但是能够直接调试还是最直观的.所有就有了本次尝试. 因调试设置源代码调试太辍笔,所以 ...

  10. Docker aufs存储驱动layer、diff、mnt目录的区别

    Docker基础信息 首先,先查询Docker使用的后端存储.使用命令docker info,主要关注Storage Driver相关的部分. $ docker info ... Server Ver ...