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. Jquery ajax, Axios, Fetch区别

    1.   Jquery ajax, Axios, Fetch区别之我见 2.   ajax.axios.fetch之间的详细区别以及优缺点

  2. js验证码有效时间倒计时

    js验证码有效时间倒计时 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type& ...

  3. js方法的使用(z)

    http://www.108js.com/article/article1/10025.html?id=58 javascript中正则匹配有3个方法,match,exec,test.这些方法都跟字符 ...

  4. Python RawSocket Syn

    #!/bin/env python # -*- coding: UTF-8 -*- # 必须以root权限运行 import socket import sys import time import ...

  5. Robot Framework环境搭建(问题总结)

    Robot Framework+python+wxpython+robotframework-ride+library环境搭建问题总结 因为robotframework的兼容性问题要求很严格,小编在环 ...

  6. Derby的jar说明

    Derby的jar说明 Derby的下载后,解压发现lib中有很多jar包,下面说明一下每个jar包的用途: 引擎库 derby.jar是引擎库,必须的 For embedded databases. ...

  7. 资料汇总--Web前端

    01.前端技能汇总 02.gitHub优秀前端资料分享 03.大前端 HTML Doctype作用?严格模式与混杂模式如何区分?它们有何意义? 1. <!DOCTYPE> 声明位于文档中的 ...

  8. EPPlus导入导出不占用进程

    导入: using (ExcelPackage package = new ExcelPackage(new FileStream(openFile.FileName, FileMode.Open, ...

  9. VS快捷键设置无效

    使用Resharper 后发现有些快捷键冲突,但是在工具-选项-键盘 设置后不管用,后来发现有一个移除功能,即移走原来的快捷键; 先选择下拉框1中自己用不到的快捷键,然后移除掉; 备注: 注意观察 快 ...

  10. nodejs图片裁剪、水印(使用images)

    /** * Created by chaozhou on 2015/9/21. */ var images = require("images"); /** * 缩放图像 * @p ...