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 解答的更多相关文章

  1. LeetCode之“动态规划”:Minimum Path Sum && Unique Paths && Unique Paths II

    之所以将这三道题放在一起,是因为这三道题非常类似. 1. Minimum Path Sum 题目链接 题目要求: Given a m x n grid filled with non-negative ...

  2. 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 ...

  3. 刷题64. Minimum Path Sum

    一.题目说明 题目64. Minimum Path Sum,给一个m*n矩阵,每个元素的值非负,计算从左上角到右下角的最小路径和.难度是Medium! 二.我的解答 乍一看,这个是计算最短路径的,迪杰 ...

  4. 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 ...

  5. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  6. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  7. [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. ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. Video.js网页视频播放插件

        插件描述:Video.js 是一个通用的在网页上嵌入视频播放器的 JS 库,Video.js 自动检测浏览器对 HTML5 的支持情况,如果不支持 HTML5 则自动使用 Flash 播放器. ...

  2. poj 1149 pigs(最大流)

    题目大意:迈克在农场工作,农场有 m 个猪舍,每个猪舍有若干只猪,但是迈克不能打开任何一间猪舍.有 n 个顾客前来购买,每个顾客有最大的购买数量,每个顾客可以购买某些猪舍的猪,且顾客可以打开这些猪舍, ...

  3. HDOJ-1019 Least Common Multiple

    http://acm.hdu.edu.cn/showproblem.php?pid=1019 题意:给出n个数,求它们的最小公倍数 对于n个数,它们的最小公倍数等于[前n-1个数的最小公倍数和第n个数 ...

  4. Unity编辑器-创建单独编辑框,折叠框,提示框

    今天我们就来学习如何创建一个编辑框,上面绘制一个折叠框里面有四种消息框. 代码如下: using UnityEngine; using System.Collections; using UnityE ...

  5. python高级编程(第12章:优化学习)1

    # -*- coding: utf-8 -*-# python:2.x__author__ = 'Administrator'#由于5,6,7,8,9,10,11主要是在包,测试之类的学习所以这边就不 ...

  6. Javascript 中的变量

    var a; console.log("The value of a is " + a); // The value of a is undefined console.log(& ...

  7. STL中map,set的基本用法示例

    本文主要是使用了STL中德map和set两个容器,使用了它们本身的一些功能函数(包括迭代器),介绍了它们的基本使用方式,是一个使用熟悉的过程. map的基本使用: #include "std ...

  8. JS实现下拉框选中不同的项,对应显示不同的信息

    实现的效果如下图: 页面代码 下拉框: <select id="select3" name="select3" onchange="showli ...

  9. sqlserver 执行远程数据库代码

    1.启用Ad Hoc Distributed Queries: exec sp_configure 'show advanced options',1reconfigureexec sp_config ...

  10. 获取UILabel上最后一个字符串的位置。获取文字长度和高度,自动换行

    //行的高度. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPat ...