Code: Select all
#include <iostream>
using namespace std;
template <class ValueType> class ZKTreeNode{
private:
ValueType m_value;
ZKTreeNode<ValueType>* m_parent;
ZKTreeNode<ValueType>* m_lch;
ZKTreeNode<ValueType>* m_rch;
public:
ZKTreeNode(){
m_parent = NULL;
m_lch = NULL;
m_rch = NULL;
}
ZKTreeNode<ValueType>* parent(){
return m_parent;
}
ZKTreeNode<ValueType>* lch(){
return m_lch;
}
ZKTreeNode<ValueType>* rch(){
return m_rch;
}
void setParent(ZKTreeNode<ValueType>* parent){
m_parent = parent;
}
void setLCh(ZKTreeNode<ValueType>* lch){
m_lch = lch;
}
void setRCh(ZKTreeNode<ValueType>* rch){
m_rch = rch;
}
void setValue(ValueType& value){
m_value = value;
}
};
template <class ValueType> class ZKBinaryTree{
private:
ZKTreeNode<ValueType>* m_root;
void clearSubTree(ZKTreeNode<ValueType>* root){
if(root != NULL){
clearSubTree(root->lch());
clearSubTree(root->rch());
delete root;
}
}
public:
ZKBinaryTree(){
m_root = NULL;
}
~ZKBinaryTree(){
clear();
}
void clear(){
clearSubTree(m_root);
m_root = NULL;
}
void init(ValueType rootValue){
clear();
m_root = new ZKTreeNode<ValueType>;
m_root->setValue(rootValue);
}
ZKTreeNode<ValueType>* root(){
return m_root;
}
};
template <class ValueType> class ZKTree : public ZKBinaryTree<ValueType>{
public:
ZKTreeNode<ValueType>* childHead(ZKTreeNode<ValueType>* root){
return root->lch();
}
ZKTreeNode<ValueType>* nextCousin(ZKTreeNode<ValueType>* node){
return node->rch();
}
ZKTreeNode<ValueType>* preCousin(ZKTreeNode<ValueType>* node){
ZKTreeNode<ValueType>* cousin;
ZKTreeNode<ValueType>* parent = node->parent();
cousin = (node == parent->rch())? parent: NULL;
return cousin;
}
//新添加子节点(加在最左边)
void addChild(ZKTreeNode<ValueType>* root, ValueType value){
ZKTreeNode<ValueType>* childHead = childHead(root);
ZKTreeNode<ValueType>* newChild = new ZKTreeNode<ValueType>;
newChild->setValue(value);
root->setLCh(newChild);
newChild->setParent(root);
if(childHead != NULL){
newChild->setRCh(childHead);
childHead->setParent(newChild);
}
}
};
int main(){
ZKTree<int> tree;
tree.init(0);
ZKTreeNode<int>* p = tree.root();
tree.addChild(p, 1);
return 0;
}