Path Sum
一个二叉树,是否存在从根节点到叶子节点的路径,其节点的值的和为指定整数,如果有,打印出所有数组。
需如下树节点求和
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
JavaScript实现
window.onload = function() {
var n1 = new TreeNode(1, null, null),
n51 = new TreeNode(5, null, null),
n2 = new TreeNode(2, null, null),
n7 = new TreeNode(7, null, null),
n42 = new TreeNode(4, n51, n1),
n13 = new TreeNode(13, null, null),
n11 = new TreeNode(11, n7, n2),
n8 = new TreeNode(8, n13, n42),
n4 = new TreeNode(4, n11, null),
n5 = new TreeNode(5, n4, n8);
var sum = 22;
var res = getPathSum(n5, sum);
console.log('res: ', res);
var has = hasPathSum(n5,22);
console.log('has: ', has);
var count = pathCount(n5,22);
console.log('count: ', count);
}
function TreeNode(val, left, right) {
this.val = val;
this.left = left;
this.right = right;
}
//path sum i(https://leetcode-cn.com/problems/path-sum-i/)
function hasPathSum(root, sum) {
if (root == null) return false;
sum -= root.val;
if (sum == 0 && root.left == null && root.right == null) return true;
return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
}
//path sum ii(https://leetcode-cn.com/problems/path-sum-ii/)
function getPathSum(root, sum) {
var res = [],path = [];
dfs(root, sum, path, res);
return res;
}
function dfs(root,sum,path,res){
if(root == null) return;
sum -= root.val;
path.push(root.val);
if(sum == 0 && root.left == null && root.right == null){
res.push(copy(path));
//这句可以加,也可以不加, 加上,可以减少后面的两个dfs内部的null判断,因为此时root的left和right都为null
return path.pop();
}
dfs(root.left,sum,path,res);
dfs(root.right,sum,path,res);
path.pop();
}
function copy(a){
return JSON.parse(JSON.stringify(a))
}
//path sum iii(https://leetcode-cn.com/problems/path-sum-iii/)
function pathCount(root,sum){
return helper(root,sum,[],0);
}
//思路就是,深度优先遍历所有节点,用path记录从根节点到该节点的路径
//由于只计算从上到下的节点和,所以从当前节点沿着path向上求和
//到合适的节点就计数,直至到根节点,当前节点为终点的所有路径计数完毕
function helper(root,sum,path,p){
if(root == null) return 0;
//记录当前节点的值
path[p] = root.val;
//path此时记录的是根节点到当前节点的路径上的所有节点
let temp = 0, n=0;
//p是当前节点的位置,从当前节点开始向根节点一路做加法
for(let i=p;i>=0;i--){
temp += path[i];
//当前节点加到某节点符合,就计数,由于节点值可能为0或负值,此处不能break,还需继续计算
if(temp == sum) n++;
}
//path虽然是引用传递,但是left和right用的是同一个索引p+1,所以path中的值会被覆盖
//path中的值始终是到当前节点的路径值,不需要拷贝数组,也不需要弹出已经访问的值
let left = helper(root.left,sum,path,p+1);
let right = helper(root.right,sum,path,p+1);
return n + left + right;
}
Path Sum的更多相关文章
- 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 ...
- Path Sum II
Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals ...
- [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]Path Sum II
Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals ...
随机推荐
- Redis学习笔记3-Redis5个可执行程序命令的使用
在redis安装文章中,说到安装好redis后,在/usr/local/bin下有5个关于redis的可执行程序.下面关于这5个可执行程序命令的详细说明. redis-server Redis服务器的 ...
- UNIX文件的权限之“设置用户ID位”
用stat函数可以获取一个文件的状态信息,原型是这样的: int stat(const char *path, struct stat *buf); 其中结构体stat的结构: struct stat ...
- JSP连接数据库,报Unable to compile class for JSP
先看一下报错原因: HTTP Status 500 - Unable to compile class for JSP: type Exception report message Unable to ...
- 用alarmmanager 多次发送PendingIntent
遇到如下问题 service中得一随机数 用alarmmanager 发送PendingIntent的时候,receiver收到的随机数不变. pendingintent传值经常获取到的值是第一次的值 ...
- Windows 10 新特性 -- Bing Maps 3D地图开发入门(一)
本文主要内容是讲述如何创建基于 Windows Universal App 的Windows 10 3D地图应用,涉及的Windows 10新特性包括 Bing Maps 控件.Compiled da ...
- FutureTask的使用
package org.zln.thread.pool.ft;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.ut ...
- GridView绑定Visible
hyerLinkFiled的显示绑定方式 ,强制类型转换后再绑定! Visible='<%#Convert.ToBoolean(Eval("字段名")) %>'
- oracle如何清空一个用户下的所有表中的数据?
-- 大概 这个样子,如果没有 FK 的话,一下子就都删掉了. begin for x in (select table_name from user_tables) loop execute imm ...
- 为什么Java不支持多继承?
没想过面试的时候,会遇到语言设计上的问题.现场答得并不好因为一直没思考过,经过了点搜索,渐渐有点思路. 1. 避免“钻石型”多继承问题:有两个类B和C继承自A.假设B和C都继承了A的方法并且进行了覆盖 ...
- swift上传头像
很久没有写博客了,今天特地写了这个,也是一边仿照别人写的demo,注释部分都是需要的.需要的同学可以参考一下. @IBAction func headImageBtnPage(){ //上传头像 / ...