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.

递归的解法:

只考虑当前结点的成败条件,对于儿子,则交给递归去做。

读到某个结点,计算路径val之和,之后判断,如果不是叶子结点,递归调用函数进入其子孙结点。如果是叶子结点,当val之和与sum值相等,返回true,不相等返回false。

注意:

1、注意题目是“root-to-leaf”即计算根节点到叶子节点的加和,不要只计算到某个枝干,即使运算到某个枝干时,sum值已经相等,也不能返回true;

2、注意可能出现正数负数混杂的情况;

 /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if (!root)
return false; int curSum = sum - root->val; if (!root->left && !root->right && curSum == )
return true; return hasPathSum(root->left, curSum) || \
hasPathSum(root->right, curSum); }
};

迭代的解法:

 class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
stack<TreeNode *> nodeStack;
TreeNode *preNode = NULL;
TreeNode *curNode = root;
int curSum = ; while (curNode || !nodeStack.empty()) {
while (curNode) {
nodeStack.push(curNode);
curSum += curNode->val;
curNode = curNode->left;
} curNode = nodeStack.top(); if (curNode->left == NULL && \
     curNode->right == NULL && \
     curSum == sum) {
return true;
} if (curNode->right && preNode != curNode->right) {
curNode = curNode->right;
} else {
preNode = curNode;
nodeStack.pop();
curSum -= curNode->val;
curNode = NULL;
}
}
return false;
}
};

附录:

用迭代法遍历二叉树思路总结

【Leetcode】【Easy】Path Sum的更多相关文章

  1. 【LeetCode题意分析&解答】40. Combination Sum II

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  2. 【LeetCode题意分析&解答】37. Sudoku Solver

    Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...

  3. 【LeetCode题意分析&解答】35. Search Insert Position

    Given a sorted array and a target value, return the index if the target is found. If not, return the ...

  4. 【LeetCode OJ】Binary Tree Maximum Path Sum

    Problem Link: http://oj.leetcode.com/problems/binary-tree-maximum-path-sum/ For any path P in a bina ...

  5. 【LeetCode】112. 路径总和 Path Sum 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS 回溯 BFS 栈 日期 题目地址:https ...

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

  7. 【leetcode】Binary Tree Maximum Path Sum (medium)

    Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. ...

  8. ACM金牌选手整理的【LeetCode刷题顺序】

    算法和数据结构知识点图 首先,了解算法和数据结构有哪些知识点,在后面的学习中有 大局观,对学习和刷题十分有帮助. 下面是我花了一天时间花的算法和数据结构的知识结构,大家可以看看. 后面是为大家 精心挑 ...

  9. 【leetcode刷题笔记】Triangle

    Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent n ...

  10. leetcode@ [124] Binary Tree Maximum Path Sum (DFS)

    https://leetcode.com/problems/binary-tree-maximum-path-sum/ Given a binary tree, find the maximum pa ...

随机推荐

  1. 【OpenCV-Python】-几何变换

    涉及函数: cv2.getPerspectiveTransform()cv2.warpAffine() 接收的参数是2✖️3的变换矩阵cv2.warpPerspective() 接收的参数是3✖️3的 ...

  2. 百度ECharts数据绑定诀窍

    百度Echarts的功能还是蛮好用的.. 不能说多好但是也不次.. 下边就分享一些数据绑定经验..对在处理过程中的思路有一些帮助... 报表里用的最多的可以说是 饼状图和柱形图.. 饼状图里当然是包括 ...

  3. 那些H5用到的技术(4)——弹幕

    前言思路实现模式无限循环模式时间线模式停止显示弹幕 前言 以前玩卷轴射击游戏的时候,大量的BOSS子弹让我们无路可逃的时候,让我见识到了真正弹幕的威力,可自从A站B站火了之后,大量评论留言参与到了视频 ...

  4. (转)[InnoDB系列] -- SHOW INNODB STATUS 探秘

    原文:http://imysql.cn/2008_05_22_walk_through_show_innodb_status 很多人让我来阐述一下 SHOW INNODB STATUS 的输出信息, ...

  5. asp.net WebService技术简介

    1.什么是web service? 这里借助百度百科专业的解释:web service是一个平台独立的.低耦合的.自包含的.基于可编程的web应用程序(说简单点,就是使用web service继续不需 ...

  6. android LinearLayoutForListView

    由于 scrollview 套 listview 会有很多问题,网上很多人用 LinearLayout 模拟 listview, 也可以设置 adapter. 很多人直接继承 BaseAdapter, ...

  7. 转 shell中$(( )) 与 $( ) 还有${ }的区别

    原文 http://blog.zol.com.cn/2322/article_2321763.html $( ) 与 ` ` (反引号)在 bash shell 中,$( ) 与 ` ` (反引号) ...

  8. 存储器的保护(三)——《x86汇编语言:从实模式到保护模式》读书笔记20

    存储器的保护(三) 修改本章代码清单,使之可以检测1MB以上的内存空间(从地址0x0010_0000开始,不考虑高速缓存的影响).要求:对内存的读写按双字的长度进行,并在检测的同时显示已检测的内存数量 ...

  9. 2-3 树/红黑树(red-black tree)

    2-3 tree 2-3树节点: null节点,null节点到根节点的距离都是相同的,所以2-3数是平衡树 2叉节点,有两个分树,节点中有一个元素,左树元素更小,右树元素节点更大 3叉节点,有三个子树 ...

  10. js 验证字符串是否全为中文

    js 验证字符串是否全为中文: function isChinese(str) { var reg = /^[\u4E00-\u9FA5]+$/; if(reg.test(str)){ return ...