编程练习——二叉树(BinaryTree)
先写一个树节点类。使用Temple也可以,不使用的话,使用特定类型,用法比较局限。不过本着“今天尽量不要做出今天不必要的决定”极限编程法制。做一个特殊类型的
BinaryTree,也未尝不可。
这里的TreeNode只有数据域。
- template < class T>
- class TreeNode
- {
- private :
- T data;
- TreeNode
* left; - TreeNode
* right; - public :
-
-
- TreeNode(T& data)
-
- {
- this ->data = data;
- this ->left = NULL;
- this ->right = NULL;
- }
-
- TreeNode(T& data,TreeNode
* left, TreeNode * right)
- TreeNode(T& data,TreeNode
- {
- this ->data = data;
- this ->left = left;
- this ->right = right;
- }
-
- ~TreeNode()
- {
-
- this ->left = NULL;
- this ->right = NULL;
- cout << “node (” << this ->data<< “) destory!” <<endl;
- // to do
- }
-
- T getData()
- {
- return data;
- }
-
- void setData(T& data)
- {
- this ->data = data;
- }
-
- TreeNode
* getLeft()
- TreeNode
- {
- return left;
- }
-
- void setLeft(TreeNode
* left)
- void setLeft(TreeNode
- {
- this ->left = left;
-
- }
-
- TreeNode
* getRight()
- TreeNode
- {
- return right;
- }
-
- void setRight(TreeNode
* right)
- void setRight(TreeNode
- {
- this ->right = right;
- }
-
-
- };
-
-
- 下面是BinaryTree的实现。一般来说,一个BinaryTree最重要的函数就是构造和析构。基本的函数是遍历。
下面的类只实现了中序遍历,和树形打印。析构删除节点使用的是后序删除法。
- template < class T>
- class BinaryTree
- {
- protected :
- TreeNode
* head; -
- void clearSubTree(TreeNode
* node)
- void clearSubTree(TreeNode
- {
- if (node != NULL)
- {
- clearSubTree(node->getLeft());
- clearSubTree(node->getRight());
- delete node;
- }
- }
-
- void printTree(TreeNode
* subTree, int count)
- void printTree(TreeNode
- {
- if (subTree!=NULL)
- {
-
- printTree(subTree->getRight(), count+1);
- for ( int i = 0; i < count; i++)
- {
- cout << " " ;
- }
- cout <
getData()<<endl; - printTree(subTree->getLeft(),count+1);
- }
- }
-
-
- void printInMidOrder(TreeNode
* subTree)
- void printInMidOrder(TreeNode
-
- {
- if (subTree!=NULL)
- {
- printInMidOrder(subTree->getLeft());
-
-
- cout <
getData()<<endl;
- cout <
-
- printInMidOrder(subTree->getRight());
- }
- }
- public :
- BinaryTree(T& data)
- {
- head = new TreeNode
(data); - }
-
- BinaryTree(TreeNode
* head)
- BinaryTree(TreeNode
- {
- this ->head = head;
- }
-
- ~BinaryTree()
- {
- clearSubTree(head);
- }
-
- void printTree()
- {
- printTree( this ->head,0);
- }
-
- void printInMidOrder()
- {
- printInMidOrder( this ->head);
- }
- };
-
- 如果BinaryTree中还有插入删除操作就好了。但是如何插入,如何删除必须按照一定的规则进行。所以就有后面的二叉查找树、AVLTree、SplayTree、RedBlackTree等各种类型的二叉树。