【Leetcode】【Easy】Path Sum
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的更多相关文章
- 【LeetCode题意分析&解答】40. Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
- 【LeetCode题意分析&解答】37. Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...
- 【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 ...
- 【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 ...
- 【LeetCode】112. 路径总和 Path Sum 解题报告(Java & Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS 回溯 BFS 栈 日期 题目地址:https ...
- 【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 ...
- 【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. ...
- ACM金牌选手整理的【LeetCode刷题顺序】
算法和数据结构知识点图 首先,了解算法和数据结构有哪些知识点,在后面的学习中有 大局观,对学习和刷题十分有帮助. 下面是我花了一天时间花的算法和数据结构的知识结构,大家可以看看. 后面是为大家 精心挑 ...
- 【leetcode刷题笔记】Triangle
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent n ...
- 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 ...
随机推荐
- TR-069_Amendment-4:附录G.穿越NAT网关的连接请求方式
注意:这种机制只适用于RFC 3489[21]中定义的经典STUN,RFC 5389引入后,这个机制已经过时.这个机制不是设计用于RFC 5389中定义的STUN.IPv6部署要么不使用NAT,要么以 ...
- MyBatis逆向工程详细教程
1 导入逆向工程到eclipse中 2 修改配置文件 注意修改以下几点: 修改要生成的数据库表 pojo文件所在包路径 Mapper所在的包路径 配置文件如下: <?xml version=&q ...
- ORA-XXXX错误集合
第一.ORA-12514:listener does not currently know of service requested in connect descriptor 监听器巴拉巴拉一堆,然 ...
- oracle系统包——dbms_random用法
oracle中随机数的包的源文件目录:{oracle_home}\rdbms\admin\dbmsrand.sql 1.返回0~1间的随机数(包括0和1)sql> select dbms_ran ...
- PHP正则表达式(转载)
这个星期要攻破PHP正则表达式 正则表达式定义 正则表达式(regular expression)描述了一种字符串匹配的模式,可以用来检查一个串是否含有某种子串.将匹配的子串做替换或者从某个串中取 ...
- hibernate的中的查询与级联操作
1.Criteria查询接口适用于组合多个限制条件来搜索一个查询集. 要使用Criteria,需要遵循以下步骤: *创建查询接口: Criteria criteria=session.createCr ...
- C指针总结
取内容* 从右至左 取地址& 从右至左 同类型指针变量关系运算是有意义的. 指针变量和数组名都表示数组的地址,但是数组名是地址常量. *p++和(*p)++不同.*p++的赋值结果跟*p相同, ...
- Codeforces 156 A——Message——————【思维题】
A. Message time limit per test 2 seconds memory limit per test 256 megabytes input standard input ou ...
- Java 实例 - 标签(Label)
Java 实例 Java 中的标签是为循环设计的,是为了在多重循环中方便的使用break 和coutinue . 以下实例当在循环中使用 break 或 continue 循环时跳到指定的标签处: ...
- sp里拼接html table标签
DECLARE @xml NVARCHAR(MAX) --generate mail body SET @xml = CAST(( SELECT --[ID] 'td','' -- ,[Status] ...