深搜,再匹配
/*Given a binary search tree, design an algorithm which creates a linked list of all the
nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists)
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Node{
public:
int data;
Node *lchild,*rchild;
Node(int a=0, Node* l= 0, Node* r = 0):data(a),lchild(l),rchild(r){}
};
class Tree{
public:
Node* root;
Tree():root(0){}
Tree(int ar[],int l){
root = 0;
for(int i = 0; i<l; i++)
insert(ar[i]);
}
void insert(int);
bool is_empty(){ return !root;}
void preorder(Node*,string&);
void destroy(Node*);
};
void Tree::insert(int k){
if(is_empty())
root = new Node(k);
else{
Node* temp = root;
Node* parent;
while(temp){
parent =temp;
if(temp->data > k)
temp = temp->lchild;
else temp = temp->rchild;
}
temp = new Node(k);
if(parent->data > k)
parent->lchild = temp;
else parent->rchild = temp;
}
}
void Tree::preorder(Node* r,string& st)
{
if(r){
preorder(r->lchild,st);
stringstream ss;
ss<<r->data;
st = st + " "+ss.str();
preorder(r->rchild,st);
}
}
void Tree::destroy(Node* r){
if(r){
destroy(r->lchild);
destroy(r->rchild);
delete r;
}
}
int main(){
int ar[]={16,423,5,67,8,9,45,78,777,33,12,11,76,4,43,7};
int a2[]={67,45,33,43,78,76};
Tree ll(ar,16);
Tree l2(a2,6);
string st1="",st2="";
ll.preorder(ll.root,st1);
l2.preorder(l2.root,st2);
int found = st1.find(st2);
if(found != string::npos)
cout<<"True"<<endl;
else cout<<"Flase"<<endl;
ll.destroy(ll.root);
l2.destroy(l2.root);
}