Path Sum 解答
Question
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.
Solution 1 -- Recursion
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
int total = 0;
return dfs(root, sum, total);
} private boolean dfs(TreeNode root, int target, int prevSum) {
if (root == null)
return false;
int currentSum = prevSum + root.val;
if (root.left == null && root.right == null) {
return currentSum == target;
} else {
return (dfs(root.left, target, currentSum) || dfs(root.right, target, currentSum));
} }
}
Solution 2 -- BFS
We can use two stacks here. One to record tree nodes. And the other to record current path sum from root to this node. Since we traverse the tree level by level. It's BFS.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
Stack<TreeNode> stack1 = new Stack<TreeNode>();
Stack<Integer> stack2 = new Stack<Integer>();
stack1.push(root);
stack2.push(0);
while (!stack1.empty()) {
TreeNode currentNode = stack1.pop();
int currentSum = stack2.pop() + currentNode.val;
if (currentNode.left == null && currentNode.right == null && currentSum == sum)
return true;
if (currentNode.left != null) {
stack1.push(currentNode.left);
stack2.push(currentSum);
}
if (currentNode.right != null) {
stack1.push(currentNode.right);
stack2.push(currentSum);
}
}
return false;
}
}
Path Sum 解答的更多相关文章
- LeetCode之“动态规划”:Minimum Path Sum && Unique Paths && Unique Paths II
之所以将这三道题放在一起,是因为这三道题非常类似. 1. Minimum Path Sum 题目链接 题目要求: Given a m x n grid filled with non-negative ...
- Path Sum II 总结DFS
https://oj.leetcode.com/problems/path-sum-ii/ Given a binary tree and a sum, find all root-to-leaf p ...
- 刷题64. Minimum Path Sum
一.题目说明 题目64. Minimum Path Sum,给一个m*n矩阵,每个元素的值非负,计算从左上角到右下角的最小路径和.难度是Medium! 二.我的解答 乍一看,这个是计算最短路径的,迪杰 ...
- Leetcode 笔记 113 - Path Sum II
题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...
- Leetcode 笔记 112 - Path Sum
题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...
- [LeetCode] Path Sum III 二叉树的路径和之三
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- [LeetCode] Binary Tree Maximum Path Sum 求二叉树的最大路径和
Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. ...
- [LeetCode] Path Sum II 二叉树路径之和之二
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- [LeetCode] Path Sum 二叉树的路径和
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...
随机推荐
- 杭电2059(dp)
龟兔赛跑 Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submis ...
- Linux 使用yum工具
Red Hat 发行版安装后无法使用yum,须注册方可使用,可以通过以下方式处理:cd /etc/yum.repos.d/备份目录下已经存在的repo文件,然后新建文件local.repo,具体脚本如 ...
- ./scripts/feeds update -a OpenWrt大招系列
./scripts/feeds update -a Updating feed 'packages' from 'https://github.com/openwrt/packages.git' .. ...
- Yii2 分页类的扩展和listview引用
Yii2 本身提供了不错分页选项供用户设置,但是实际项目中我们往往需要复杂一些的分页样式,例如下图所示的效果,上下翻页可用和不可用均用图标来替换.
- functools:管理函数工具(部分)
# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' #functools:管理函数工具 #作用:处理其他函数的函数 #版 ...
- 河内塔(hanoi)
理论: 河内塔: 1.有三根杆子A,B,C.A杆上有若干碟子 2.每次移动一块碟子,小的只能叠在大的上面 3.把所有碟子从A杆全部移到C杆上 讲解: 设A上有n个盘子.如果n=1,则将圆盘从A直接 ...
- Binarized Neural Networks_ Training Neural Networks with Weights and Activations Constrained to +1 or −1
转载请注明出处: http://www.cnblogs.com/sysuzyq/p/6248953.html by 少侠阿朱
- pat 1049 Counting Ones
要统计1到N之间‘1’的个数,如数11包含2个1.所以当N=12时,答案为5. 思想: 找规律,假设ans[N]表示1到N的‘1’的个数,则有a[100]=(a[10]-1)*9+10+a[10]-1 ...
- 将字符串变成大写----C++实现
虽然这个题目很简单,但是也是会范很多错误的,平时你肯定知道,但是在编程的时候就是容易犯傻,而且八匹马都拽不回来... 看来还是要多写写代码..不废话了. 直接贴代码.. #include<ios ...
- Android内存泄漏监测(MAT)及解决办法
http://ttlnews.blogspot.com/2010/01/attacking-memory-problems-on-android.html 这篇文章是2010年1月份写的,其中有些已经 ...