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. Spring HTTP invoker 入门

    一.简介 Spring开发团队意识到RMI服务和基于HTTP的服务(如,Hessian)之间的空白.一方面,RMI使用JAVA标准的对象序列化机制,很难穿透防火墙.另一方面,Hessian/Burla ...

  2. Micro Python - Python for microcontrollers

    Micro Python - Python for microcontrollers MicroPython

  3. 04747_Java语言程序设计(一)_第3章_面向对象编程基础

    链式编程 每次调用方法后,返回的是一个对象 /* * 链式编程 * 每次调用方法后,返回的是一个对象 */ class Student { public void study() { System.o ...

  4. 【转】ffserver用法小结

    我们可以通过ffserver以及ffmpeg做一个简单的视频监控系统,ffserver用于视频的转发调度,ffmpeg用于转码 而对于ffserver最基本也是最重要的就是对它的ffserver.co ...

  5. Uboot与Linux之间的参数传递

    U-boot会给Linux Kernel传递很多参数,如:串口,RAM,videofb等.而Linux kernel也会读取和处理这些参数.两者之间通过struct tag来传递参数. U-boot把 ...

  6. 学习笔记DAY2

    Pycharm使用 1.添加模板 file => settings =>Editor=>file and code template => python script => ...

  7. WEB服务器6--IIS架构补充篇

    第一部分我将谈谈IIS的两个不同的版本—IIS 5.x 和 IIS 6的处理模型:IIS如何监听来自外界的Http request,如何根据ISAPI Extension Mapping将对于不同Re ...

  8. js 随手记

    var name = 'frog' function hello(){ alert(name); // undefined var name = 'bbc'; } 在javascript中,函数是可以 ...

  9. H5移动端性能优化

    概述 1. PC优化手段在Mobile侧同样适用 2. 在Mobile侧我们提出三秒种渲染完成首屏指标 3. 基于第二点,首屏加载3秒完成或使用Loading 4. 基于联通3G网络平均338KB/s ...

  10. ios变量的property属性设置和意义

    IOS 的@property和@synthesize帮我们轻易的生成对象的getter和setter方法来完成对对象的赋值和访问.但是如果我们如果要动态设置对象的getter和setter方法可以使用 ...