//由于二叉树的构建中,节点只支持0~9,故accumulate暂时只支持0~9的运算
//输入格式为前序遍历,需要输入每一个空节点,以"#"的形式,eg:1234##5##6#7##89#1##2##
//再讲一句,我真厉害!~~~
#include<stack>
#include<iostream>
#include<algorithm>
using namespace std;
struct Node {
int value;
Node *left;
Node *right;
bool visit;
Node(){
left=NULL;
right=NULL;
visit=false;
}
};
//前序遍历输入建树
Node* CreatTree()
{
Node *BT;
BT=new Node;
char ch; cin>>ch;
if(ch=='#')
{
BT=NULL; return BT;
}
BT->value=(int)(ch-'0');
BT->left=CreatTree();
BT->right=CreatTree();
return BT;
}
void print(Node* T){
if(T==NULL) cout<<"#";
else{
cout<<T->value;
print(T->left);
print(T->right);
}
}
class Tree{
private:
Node* root;
public:
Tree(Node* Root):root(Root){}
class iterator_plus{
private:
stack<Node*> mStack_next;
stack<Node*> mStack_pre;
Node* ptr;
Node* next() {
if (mStack_next.empty()) {
return NULL;
}
Node *top = mStack_next.top();
mStack_next.pop();
mStack_pre.push(top);
if (!top->visit&&NULL != top->right) {
Node *current = top->right;
while (NULL != current) {
mStack_next.push(current);
current = current->left;
}
}
return top;
}
Node* pre(){
Node *top = mStack_pre.top();
top->visit=true;
mStack_pre.pop();
mStack_next.push(top);
}
public:
iterator_plus(Node *node) {//传入的是树根
Node *current = node;
while (NULL != current) {
mStack_next.push(current);
current = current->left;
}
ptr=next();
}
iterator_plus(){
ptr=NULL;
}
bool operator!=(const iterator_plus &src){return ptr != src.ptr;}
iterator_plus operator++(){ptr=next();return *this;}
iterator_plus operator++(int){iterator_plus *temp=this;ptr=next();return *temp;}
iterator_plus operator--(){ptr=pre();return *this;}
int operator*(){return ptr->value;}
// const Node* operator*()const{return *ptr;}
};
iterator_plus beginning(){return iterator_plus(root);}
iterator_plus ending(){return iterator_plus();}
};
/*struct Functor
{
int operator () (Node *i, Node *j)
{
return i->value+j->value;
}
};*/
int main(void){
Node* T=CreatTree();
Tree BinaryRoot(T);
/* for(Tree::iterator_plus i=BinaryRoot.beginning();i!=BinaryRoot.ending();i++){
cout<<*i<<" ";
}*/
cout<<"求和结果为"<<accumulate(BinaryRoot.beginning(),BinaryRoot.ending(),0)<<endl;
return 0;
}
二叉树的迭代器(以accumulate函数作为测试用例)
最新推荐文章于 2024-08-06 10:06:06 发布