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. CSAPP阅读笔记-数组分配与访问-来自第三章3.8的笔记-P176-P183

    这一节比较简单,仅记录几个比较重要的点: 1.C语言允许对指针进行运算,计算出的值会根据该指针引用的数据类型大小进行伸缩. 例子: 其中,xE是数组的起始地址.注意,指针运算时,若最终结果为指针,则指 ...

  2. javaagent笔记及一个基于javassit的应用监控程序demo

    javaagent基本用法 定义入口premain public static void premain(String agentArgs, Instrumentation inst) { Syste ...

  3. Clojure编写一个阶乘程序 使用递归

    这是递归 (def f     (fn fb     [x]    (if (< x 2)      1      (* x (fb (- x 1)) )     )        )  ) ( ...

  4. Struts2 入门介绍(一)

    一.什么是Struts2 1.Struts2是一个开发框架,应用于JavaEE三层架构中的web层. 2.Struts2框架是在Struts1和webwork基础上发展的一个全新的框架. 3.Stru ...

  5. addEventListener()和removeEventListener()

    作用: addEventListener()与removeEventListener()用于处理指定和删除事件处理程序操作. 它们都接受3个参数:事件名.事件处理的函数和布尔值. 布尔值参数是true ...

  6. bat下执行java程序报错处理

    G:\>java -Xms128M -Xmx512M -server -Dprogram.name=b omc-sa-tdtpagent -Dfile.encoding=GBK -Duser.t ...

  7. PL/SQL之流控制语句

    1.选择控制语句 --语法1--IF 条件 THEN 语句; END IF; DECLARE v_Salary ,); BEGIN SELECT salary INTO v_Salary FROM a ...

  8. java 并发(六) --- 锁

          阅读前阅读以下参考资料,文章图片或代码部分来自与参考资料 概览 一张图了解一下java锁. 注 : 阻塞将会切换线程,切换内核态和用户态,是比较大的性能开销 各种锁 为什么要设置锁的等级 ...

  9. 【Hadoop系列】linux下 root用户免密码登录远程主机 ssh

    SSH原理:[Hadoop系列]linux SSH原理解析 操作环境: CentOS 6.5 操作对象: 用户A主机和远程主机B 正文部分:斜体加粗代表linux指令. linux下 非root用户免 ...

  10. springboot+mybatis+thymeleaf+docker构建的个人站点开源项目(集成了个人主页、个人作品、个人博客)

    前言 My Site 主要功能有:个人首页.个人作品.个人博客为一体的站点,网站的文章和作品均由markdown进行编写,可以满足你的基本需求.如果觉得这个项目不错,请为它点赞支持. 项目架构 JDK ...