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 ...
随机推荐
- unix c 07
进程的结束函数 (exit._Exit) exit 并不是立即退出,退出前执行 用atexit/on_exit函数 注册的函数. exit(int status)中的status可以用 w ...
- C++字符串指针与字符数组的区别
今天发现这样一个问题 #include <iostream> using namespace std; int main() { ]; strcpy_s(ch1,");//编译通 ...
- C++ I/O标准库
C++学习: 返回指向函数的指针: int (*ff(int))(int *,int) 想写好这样的代码很难,含义:首先将ff声明为一个函数,它带有一个int形参.该函数返回 int (*)(int* ...
- Linux 通过HTTP进行域名更新
一.3322动态域名更新接口 接口地址 API URL http://members.3322.net/dyndns/update HTTP请求 GET /dyndns/update?hostname ...
- JSP通过SmartUpload上传文件实例
httpRequest.setCharacterEncoding("gbk"); String preName = genName.doMake();//设置文件前缀名 Strin ...
- 阿里云部署Docker(5)----管理和公布您的镜像
出到这节,我在百度搜索了一下"阿里云部署Docker",突然发现怎么会有人跟我写的一样呢?哦,原来是其它博客系统的爬虫来抓取,然后也不会写转载自什么什么的.所以,我最终明确为什么那 ...
- CDN云主机与传统虚拟主机功能对比
CDN云主机与传统虚拟主机功能对比 传统的虚拟主机都是单台服务器,一旦机器硬件损坏.IP被封.机房网络故障等,都将导致网站不能访问,严重的情况数据还无法及时取回,即使想换一家服务商也因为没有数据而无能 ...
- dtree基础
最近用到了dtree来建立树,纠结过好久后,终于有了些门道,下面的总结希望对咪咪们有些帮助: dtree用来建立静态树或者动态树都是很方便的,老外给提供了整个的JS,然后我们只是操心这个树中存放的元素 ...
- c#修改本地连接工具 ip地址,dns,网关,子网掩码
//Form1类后台 #region 加载配置文件中的信息 /// <summary> /// 加载配置文件中的信息 /// </s ...
- Webfrom 生成流水号 组合查询 Repeater中单选与复选控件的使用 JS实战应用
Default.aspx 网页界面 <%@ Page Language="C#" AutoE ...