在二元树中找出和为某一值的所有路径
来源:互联网 发布:电子商务网站源码下载 编辑:程序博客网 时间:2024/04/29 08:39
从根到树叶, 找出所有路径中 和为给定的路径。
先序遍历,把访问到的节点放入vector中。当递归返回时从vector中删除节点。
参考代码:
#include<iostream>
#include<vector>
using namespace std;
struct Tree
{
Tree(int num):element(num),left(NULL),right(NULL){}
int element;
Tree* left;
Tree* right;
};
Tree* init()
{
Tree *root = new Tree(10);
root->left = new Tree(5);
root->right = new Tree(12);
root->left->left = new Tree(4);
root->left->right = new Tree(7);
return root;
}
vector<Tree> node;
void find( Tree *r, int sum)
{
if(r)
{
node.push_back(*r);
}
if( r->left==NULL && r->right==NULL)
{
if(sum - r->element ==0)
{
vector<Tree>::iterator i= node.begin();
for(i; i!=node.end();i++)
cout<<i->element<<" ";
cout<<endl;
}
node.erase(node.end()-1);
}
else
{
if(r->left)
{
find(r->left, sum - r->element);
}
if(r->right)
{
find(r->right, sum- r->element);
}
node.erase(node.end()-1);
}
}
int main()
{
Tree* root = init();
find(root, 22);
return 0;
}
- 在二元树中找出和为某一值的所有路径的个人代码
- 在二元树中找出和为某一值的所有路径(树)
- 在二元树中找出和为某一值的所有路径(树)
- 4.在二元树中找出和为某一值的所有路径(树)
- No4、在二元树中找出和为某一值的所有路径(树)
- 在二元树中找出和为某一值的所有路径(树)
- 在二元树中找出和为某一值的所有路径(树)
- 4.在二元树中找出和为某一值的所有路径(树)
- 4.在二元树中找出和为某一值的所有路径(树)
- 4.在二元树中找出和为某一值的所有路径(树)
- 在二元树中找出和为某一值的所有路径-递归算法
- 在二元树中找出和为某一值的所有路径
- 在二元树中找出和为某一值的所有路径
- 在二元树中找出和为某一值的所有路径
- 算法讨论(三)---在二元树中找出和为某一值的所有路径
- 在二元树中找出和为某一值的所有路径
- 算法题23 在二元树中找出和为某一值的所有路径
- 在二元树中找出和为某一值的所有路径
- 选首领: 链表应用
- Introduction to Endianness(大端小端介绍)
- 华为编程大赛
- Linux下core文件调试方法
- html基础知识
- 在二元树中找出和为某一值的所有路径
- 两点是否在一条直线上--Java编写---点是否在三角行内
- 关于 contact aggregation & lookup uri
- c++笔记 遮掩继承
- SRM540-div2-3-FractionInDifferentBases
- struts2整合spring 时web.xml的配置
- 进程、轻量级进程(LWP)、线程
- 拷贝构造函数
- 我的时间管理——幸福密码