Nice game:
#pragma once
#include <stdio.h>
#include <tchar.h>
class TreeNode;
class vWalkTree
{
public: virtual int Enter(TreeNode* p) = 0;
virtual int Leave(TreeNode* p) = 0;
};
class TreeNode
{
public:
TreeNode(const int v,TreeNode* l=0,TreeNode* r=0){ value=v; left=l; right=r; }
~TreeNode(){ if(left) delete left; if(right) delete right; }
int get(){ return value; }
TreeNode* most_left();
TreeNode* most_right();
int compare(TreeNode* with){ return value-with->value; }
void swap(TreeNode* p){ int v=value; value=p->value; p->value=v; }
void walk(vWalkTree& w);
private:
TreeNode* left;
TreeNode* right;
int value;
};
void TreeNode::walk(vWalkTree& w)
{
if(w.Enter(this))
{
if(left) left->walk(w);
if(right) right->walk(w);
w.Leave(this);
}
}
TreeNode* TreeNode::most_left()
{
TreeNode* r;
TreeNode* l;
l = left ? left ->most_right():0;
if(l && (0>compare(l))) swap(l);
r = right ? right->most_left ():0;
if(r && (0<compare(r))) swap(r);
return left?left->most_left():this;
}
TreeNode* TreeNode::most_right()
{
TreeNode* r;
TreeNode* l;
l = left ? left ->most_right():0;
if(l && (0>compare(l))) swap(l);
r = right ? right->most_left ():0;
if(r && (0<compare(r))) swap(r);
return right?right->most_right():this;
}
int _tmain(int argc, _TCHAR* argv[])
{
TreeNode root
(
20,
new TreeNode
(
15,
new TreeNode(10,new TreeNode(9),new TreeNode(16)),
new TreeNode(17,new TreeNode(12),new TreeNode(18))
),
new TreeNode
(
30,
new TreeNode(25,new TreeNode(22),new TreeNode(26)),
new TreeNode(33,new TreeNode(31),new TreeNode(34))
)
);
class PrintTree : public vWalkTree
{
public: int Enter(TreeNode* p)
{
if(reached==level){ ++done; _tprintf(__T("%i "),p->get()); }
++reached;
return 1;
}
int Leave(TreeNode* p)
{
--reached;
return 1;
}
PrintTree(){ level=0; reached=0; done=0; }
public:
unsigned int level;
unsigned int done;
private:
unsigned int reached;
};
PrintTree walk;
_tprintf(__T("--- before ---\r\n"));
walk.level = 0;
do{ walk.done=0; root.walk(walk); ++walk.level; _tprintf(__T("\r\n")); }while(walk.done);
root.most_left();
_tprintf(__T("--- after ---\r\n"));
walk.level = 0;
do{ walk.done=0; root.walk(walk); ++walk.level; _tprintf(__T("\r\n")); }while(walk.done);
_gettch();
return 0;
}
Regards.