#include "cTree.h"

//////////////////////////////////////////////////////////////
//////////////////////////// cTree Node ///////////////////////
//////////////////////////////////////////////////////////////
template<class T> cTreeNode<T>::cTreeNode(){
	Parent = Left = Right = NULL;
}

template<class T> cTreeNode<T>::~cTreeNode(){
	Clear();
}

template<class T> void cTreeNode<T>::Clear(){
	if(Left) delete Left;
	Left = NULL;
	if(Right) delete Right;
	Right = NULL;
}
///////////////////////// Set, Add, Get ////////////////////
template<class T> void cTreeNode<T>::Set(T &nData){
	Data = nData;
}
template<class T> bool cTreeNode<T>::Add(T &nData){
	if(Data == nData){
		Data = nData;
		return true;
	}
	if(Data > nData){
		if(Left){
			Left->Add(nData);
		}else{
			Left = new cTreeNode<T>;
			if(!Left) return false;
			Left->Set(nData);
		}
	}else{
		if(Right){
			Right->Add(nData);
		}else{
			Right = new cTreeNode<T>;
			if(!Right) return false;
			Right->Set(nData);
		}
	}
	return true;
}

template<class T> bool cTreeNode<T>::Get(T &nData){
	if(Data == nData){
		nData = Data;
		return true;
	}
	if(nData < Data){
		if(Left) return Left->Get(nData);
		return false;
	}
	if(Right) return Right->Get(nData);
	return false;
}
template<class T> bool cTreeNode<T>::LinearGet(T &nData){
	if(Data == nData){
		nData = Data;
		return true;
	}
	if(Left && Left->LinearGet(nData)) return true;
	if(Right && Right->LinearGet(nData)) return true;
	return false;
}

template<class T> bool cTreeNode<T>::IsIn(T &nData){
	if(Data == nData) return true;

	if(nData < Data){
		if(Left) return Left->IsIn(nData);
		return false;
	}
	if(Right) return Right->IsIn(nData);
	return false;
}

template<class T> void cTreeNode<T>::Print(){
	if(Left) Left->Print();
	Data.Print();
	if(Right) Right->Print();

}

//////////////////////////////////////////////////////////////
/////////////////////////// cTree ////////////////////////////
//////////////////////////////////////////////////////////////
template<class T> cTree<T>::cTree(){
	Root = NULL;
}

template<class T> cTree<T>::~cTree(){
	Clear();
}

template<class T> void cTree<T>::Clear(){
	if(Root) delete Root;
	Root = NULL;
}
//////////////////////// Add, Get ////////////////////////////
template<class T> bool cTree<T>::Add(T &nData){
	if(Root) return Root->Add(nData);
	Root = new cTreeNode<T>;
	if(!Root) return false;
	Root->Set(nData);
	return true;
}

template<class T> bool cTree<T>::Get(T &Key){
	if(Root) return Root->Get(Key);
	return false;
}

template<class T> bool cTree<T>::LinearGet(T &Key){
	if(Root) return Root->LinearGet(Key);
	return false;
}

template<class T> bool cTree<T>::IsIn(T &Key){
	if(Root) return Root->IsIn(Key);
	return false;
}

template<class T> void cTree<T>::Print(){
	if(Root) Root->Print();
}

