zoukankan      html  css  js  c++  java
  • 在二元树中找出和为某一值的所有路径

    题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。

    比较纠结,整了半天非递归算法,就是没搞明白,哎,最后还是用了递归的方法,好吧....算法比较简单....

    //在二元树中找出和为某一值的所有路径
    #include<iostream>
    #include<vector>
    #include<stack>
    using namespace std;
    struct treenode{
    	int data;
    	treenode *l;
    	treenode *r;
    };
    void createtree(treenode *&tree){
    	tree=new treenode;
    	tree->data=10;
    	tree->l=new treenode;
    	tree->l->data=5;
    	tree->l->l=new treenode;
    	tree->l->l->data=4;
    	tree->l->l->l=NULL;
    	tree->l->l->r=NULL;
    	tree->l->r=new treenode;
    	tree->l->r->data=7;
    	tree->l->r->l=NULL;
    	tree->l->r->r=NULL;
    
    	tree->r=new treenode;
    	tree->r->data=12;
    	tree->r->l=NULL;
    	tree->r->r=NULL;
    }
    void Print(vector<int> &path){              //输出路径
    	for(vector<int>::iterator iter=path.begin();iter!=path.end();iter++){
    		cout<<*iter<<" ";
    	}
    	cout<<endl;
    }
    void find(treenode *tree,int cursum,const int sum,vector<int> path){ //递归寻找
    	if(tree){
    		cursum+=tree->data;
    		path.push_back(tree->data);
    		if(cursum==sum){Print(path);}
    		find(tree->l,cursum,sum,path);
    		find(tree->r,cursum,sum,path);
    		cursum-=tree->data;      //晕,一开始忘加了....递归的回溯
    		path.pop_back();
    	}
    }
    int main(void){
    	treenode *tree;
    	vector<int> path;
    	createtree(tree);
    	int sum;
    	cin>>sum;
    	find(tree,0,sum,path);
    	system("pause");
    	return 0;
    }
    
  • 相关阅读:
    数据挖掘十大经典算法
    vc++17 进程间的通信
    GOOGLE笔试题(10.15电子科大)
    解决Vmware下Linux上网问题
    Eclipse 常用快捷键
    Error: could not open `C:\Program Files\Java\jre6\lib\i386\jvm.cfg')
    linux下ERROR 1045 (28000): Access denied for user root@localhost (using password: NO)
    eclipse环境变量设置
    为什么写博客
    eclipse添加自动代码提示
  • 原文地址:https://www.cnblogs.com/aLittleBitCool/p/1937776.html
Copyright © 2011-2022 走看看