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. python入门练习之如何连接数据库

    !/usr/bin/python -- coding: UTF-8 -- author = 'luke' from sqlalchemy import create_engine from sqlal ...

  2. jstack Dump 日志文件中的线程状态(转)

    jstack Dump 日志文件中的线程状态 dump 文件里,值得关注的线程状态有: 死锁,Deadlock(重点关注)  执行中,Runnable 等待资源,Waiting on conditio ...

  3. (转)【面试】【MySQL常见问题总结】【03】

    [常见面试问题总结目录>>>] [面试][MySQL常见问题总结][03] 2016-05-29 22:20 阅读(8244) 评论(2) [面试][MySQL常见问题总结][02] ...

  4. 【lua】LWT HttpdModule

    要使用httpd模块,需要在脚本开头添加: require "httpd" httpd.pairs(apr_table) 用以遍历apr_table for key, value ...

  5. Visual Studio中判断项目的类型

    1. 打开项目的属性,查看Application的Output type

  6. WPF与Winform中的不同(1)

    1. 部分控件的Text属性,变成了 Content属性 如: winform中,Button.Text = "abc"; wpf中,Button.Content = " ...

  7. 九度oj 1001 A+B for Matrices 2011年浙江大学计算机及软件工程研究生机试真题

    题目1001:A+B for Matrices 时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:15235 解决:6172 题目描述: This time, you are supposed ...

  8. preg_match()——php

    第一,让我们看看两个特别的字符:‘^’和‘$’他们是分别用来匹配字符串的开始和结束,以下分别举例说明: "^The": 匹配以 "The"开头的字符串; &qu ...

  9. php中array_walk() 和 array_map()两个函数区别

    两个函数的共性和区别: 1.传入这两个函数的 $value,就是数组中的单一个元素. 2.array_walk() 仅返回true或者false,array_map() 返回处理后的数组: 3.要得到 ...

  10. UML关系

    UML关系详解 1.关联关系(association) 连接模型元素及链接实例,用一条实线来表示 2.依赖关系(dependency) 表示一个元素以某种方式依赖于另一个元素,用一条虚线加箭头来表示 ...