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. goledengate重新投递和目标端跳过过事务

    日常在goledengate的维护中,最大的问题莫过于进程ABENDING.在我的维护生涯中,主要的有两个原因,第一个是网络中断造成的造成的文件损坏,一个是大事务(相关操作人员在进行操作的时候事务过大 ...

  2. Python+Selenium之cannot focus element 解决方法

    有时候刚进入页面输入第一个值时脚本会报错:cannot focus element 贴下我的脚本和解决办法供大家参考 我原本的脚本是: WebDriverWait(driver,15,0.5).unt ...

  3. 移动工程后,打开ROM核无配置信息

    问题: 从他人处下载的ISE工程,打开dw51的ROM IP核,无配置信息,为block memory generator的初始配置,并显示无法找到coe文件 原因:ROM配置过程中的部分内容丢失导致 ...

  4. 750的设计图以rem为单位的移动设备响应的设置大小

    750的设计图,设置font-size: 125%;  1rem =20px;  大部分浏览器默认的字体大小为16px,谷歌默认字体大小为12px; 其他设备的fon-size的比列: 320/720 ...

  5. MySQL修改数据表

    ALTER [IGNORE] table tb_name alter_spec,alter_spec......... alter_specification: ADD [COLUMN] create ...

  6. selenium+Python(生成html测试报告)

    当自动化测试完成后,我们需要一份漂亮且通俗易懂的测试报告来展示自动化测试成果,仅仅一个简单的log文件是不够的 HTMLTestRunner是Python标准库unittest单元测试框架的一个扩展, ...

  7. javascript记住用户名和登录密码

    javascript记住用户名和登录密码 下面主要通过代码给大家展示下javascript记住用户名和登录密码,具体代码内容请看下文. <script type="text/javas ...

  8. Ubuntu16.04 静态IP配置

    Ubuntu16.04 静态IP配置 修改配置 登录系统后,编辑文件/etc/network/interfaces.原始的内容如下: # This file describes the network ...

  9. touch-slide-image

    用htmls5+css3实现的在android和ios,以及wekit新版浏览器上实现手指滑动切换图片. https://github.com/navyxie/touch-slide-image

  10. java启动线程时 extends与implements的一个差异

    java extends与implements在使用时的一个差异: Implements: public class ThreadImplementsTest implements Runnable{ ...