[LeetCode] 路径和 Path Sum
来源:互联网 发布:js声明二维数组 编辑:程序博客网 时间:2024/05/17 02:21
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree and
sum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5]]思路:从上往下递归,递归的过程中保存每个节点的值,并且从sum里减去该节点的值,将新的sum向下传递。递归到叶子节点的时候,如果叶子节点和sum相等,那么所经过的路径就是一个符合要求的路径。(为了把所有符合要求的路径聚集在一起,下面的算法用了一个按引用传递的变量 vector<vector<int>>& paths).代码如下:
vector<vector<int> > pathSum(TreeNode *root, int sum) { // main function vector<vector<int>> paths; vector<int> path; hasPathSumUtil(root, sum, path, paths ); return paths; } bool hasPathSumUtil(TreeNode *root, int sum, vector<int> path, vector<vector<int>>& paths ) { // utility function if(root==NULL) return false; path.push_back(root->val); // store the nodes along each path if(root->left==NULL && root->right==NULL) // if we reach a leaf node if(root->val == sum) { paths.push_back(path); // we have find a valid path return true; } else return false; // this path is not valid bool leftHas = hasPathSumUtil(root->left, sum - root->val, path, paths); bool rightHas = hasPathSumUtil(root->right, sum - root->val, path, paths); if(leftHas || rightHas) return true; else return false; }
0 0
- LeetCode Path Sum 路径和
- [LeetCode] 路径和 Path Sum
- leetcode Path Sum 路径和
- Path Sum 二叉树路径和 @LeetCode
- LeetCode Path Sum II路径和II
- [leetcode]Minimum Path Sum 最小路径和
- Leetcode:Minimum Path Sum 最小路径和
- LeetCode | Path Sum(路径和)
- LeetCode 112. Path Sum(路径和)
- LeetCode-112-Path Sum(路径和)
- 【leetcode 二叉树路径和】Path Sum 和 Path Sum II
- Minimum Path Sum 矩阵最短路径和@LeetCode
- LeetCode | Path Sum II(路径和2)
- LeetCode | Minimum Path Sum(最小路径和)
- LeetCode OJ 之 Path Sum(求路径和)
- LeetCode OJ 之 Path Sum II (路径和 - 二)
- LeetCode OJ 之 Minimum Path Sum (最小路径和)
- LeetCode (12) Path Sum (二叉树路径和判断)
- PostgreSQL学习笔记2 - 部分命令备忘
- 8叉树量化
- 设计模式之单例模式、命令模式浅析
- Monit监控工具的使用
- FFmpeg和SDL教程之一(Making Screencaps)
- [LeetCode] 路径和 Path Sum
- 【博客管理】博客目录导航【置顶】
- 简易图片浏览器
- 使用XFire开发WebService
- 黑马程序员--Java基础之IO包中的其他一些类
- onInterceptTouchEvent与onTouchEvent的调用时序
- 【MongoDB】MongoDB数据库之海量存储机制
- new的指针引用
- 交叉排序