二叉树的路径和
来源:互联网 发布:淘宝价格区间设置不了 编辑:程序博客网 时间:2024/06/05 20:07
1.问题描述:
给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值
的路径。
一个有效的路径,指的是从根节点到叶节点的路径
2.思路:遍历二叉树的所有路径,并储存在vector中,如果和等于目标值,则返回这个vector。
3.代码:
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /** * @param root the root of binary tree * @param target an integer * @return all valid paths */ vector<vector<int>> ve; void PathSum(TreeNode*root,int sum,int goal,vector<int> v) { if(root->left==NULL&&root->right==NULL) { if(sum==goal) ve.push_back(v); return;} int s; if(root->left!=NULL) { vector<int> vv(v); s=sum+root->left->val; vv.push_back(root->left->val); PathSum(root->left,s,goal,vv);} if(root->right!=NULL) { vector<int> vv(v); s=sum+root->right->val; vv.push_back(root->right->val); PathSum(root->right,s,goal,vv);} } vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) { // Write your code here if(root==NULL) return ve; vector<int> v; v.push_back(root->val); PathSum(root,root->val,target,v); return ve; }};
4.感想:最后写的这几个程序都比之前的复杂一些,都需要查资料才能明白怎么写~
0 0
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- angular2学习笔记(6)
- HDU 1789 Doing Homework again(贪心)
- 属性动画 向右消失 向左出来
- skynet 控制台管理使用技巧
- Confluence安装
- 二叉树的路径和
- Hibernate框架学习(三) 关系映射
- HttpClient与HttpURLConnection分析
- 程序员好的记录
- Android开发中常见adb命令的使用
- Python的collections模块及namedtuple详解
- ubuntu下带CUDA的OpenCV安装
- js开发实现简单贪吃蛇游戏(20行代码)
- JavaScript 面向对象编程