二叉树的路径和
来源:互联网 发布:淘宝宝贝导出excel 编辑:程序博客网 时间:2024/06/05 18:39
一.题目描述
给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值
的路径。
一个有效的路径,指的是从根节点到叶节点的路径。
样例给定一个二叉树,和 目标值 = 5
:
1 / \ 2 4 / \ 2 3
返回:
[ [1, 2, 2], [1, 4]]
计算每条路径的节点数,与给定值比较,若相等则把该条路径插到双重向量容器的末尾.
三.实现代码
/** * 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>> binaryTreePathSum(TreeNode *root, int target) { // Write your code here vector<vector<int> >paths; vector<int>path; vector<int>::iterator it; if(root==NULL) { return paths; } else { ff(root,paths,path,target); return paths; } } void ff(TreeNode*root,vector<vector<int> >&paths,vector<int>p,int target){ p.push_back(root->val); vector<int>::iterator itp; if(root->left==NULL&&root->right==NULL) { int flag=0; for(itp=p.begin();itp!=p.end();itp++) { flag+=*itp; } if(flag==target) { paths.push_back(p); } } if(root->left!=NULL) { ff(root->left,paths,p,target);} if(root->right!=NULL) { ff(root->right,paths,p,target);} }};
四.感悟
这道题与二叉树的所有路径相似,只需要在其基础上把路径的节点数相加与给定值比较,把符合条件的路径放在向量容器中.
0 0
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 栈ADT
- C++ 模板学习总结(二)基本概念、实例化和具体化
- 字串和
- 【软考】设计模式-原型模式
- 浙江省赛 C What Kind of Friends Are You?
- 二叉树的路径和
- ZOJ 142
- header 跳转
- 《数据结构之树篇》--二叉树的链表实现
- cut工具
- Java实现数据结构--栈
- java 中常见的几种算法,解释很详细
- 19.嵌套的监控程序锁死
- hdu4497——GCD and LCM(数论&容斥原理or排列组合)