/* * Copyright (c) 2010,hnu-software * All rights reserved. * * 文件名称:binarytree.h * 文件标识:.h * 摘 要:二叉查找树的一个简单定义 * * 当前版本:1.1 * 作 者:www * 完成日期: */ #ifndef BINARYTREE_H #define BINARYTREE_H template<class Elem> class TreeNode //树的节点的定义 { public: Elem element;//树中节点包含的值 TreeNode<Elem>*left;//指向左子树的指针 TreeNode<Elem>*right;//指向右子树的指针 TreeNode() { left=NULL; right=NULL; } TreeNode(Elem item) { element=item; left=NULL; right=NULL; } }; template<class Elem> class BinaryTree { private: TreeNode<Elem>*root; int size; void inorder(TreeNode<Elem>*root);//中序遍历 void preorder(TreeNode<Elem>*root);//前序遍历 void postorder(TreeNode<Elem>*root);//后序遍历 public: BinaryTree(); BinaryTree(Elem elements[],int arraysize);//用一个数组初始化树 bool insert(Elem element);//将一个元素插入树中 void inorder(); void preorder(); void postorder(); int getSize(); TreeNode<Elem>* inorderFirstLeaf(); bool isLength(); }; template<class Elem> BinaryTree<Elem>::BinaryTree() { root=NULL; size=0; } template<class Elem> BinaryTree<Elem>::BinaryTree(Elem elements[],int arraysize) { root=NULL; size=0; for(int i=0;i<arraysize;i++) { insert(elements[i]); } } /*向二叉树中插入元素,成功返回TRUE,不成功返回FALSE*/ /*若二叉树为空,则创建根节点保存新数据元素。否则定位新数据元素节点的父节点。 *若新元素小于父节点中的元素,作为父节点的左孩子,否则为右孩子 */ template<class Elem> bool BinaryTree<Elem>::insert(Elem element) { if(root==NULL) root=new TreeNode<Elem>(element); else { TreeNode<Elem>*parent=NULL; TreeNode<Elem>*current=root; while(current!=NULL) { if(element<current->element) { parent=current; current=current->left; } else if(element>current->element) { parent=current; current=current->right; } else return false; }//else结束后所要插入的位置的父节点为parent if(element<parent->element) parent->left=new TreeNode<Elem>(element); else parent->right=new TreeNode<Elem>(element); } size++; return true; } //中序遍历 template<class Elem> void BinaryTree<Elem>::inorder(TreeNode<Elem>*root) { if(root==NULL) return ; inorder(root->left); cout<<root->element<<endl; inorder(root->right); } template<class Elem> void BinaryTree<Elem>::inorder() { inorder(root); } //后序遍历 template<class Elem> void BinaryTree<Elem>::postorder(TreeNode<Elem>*root) { if(root==NULL) return false; inorder(root->left); inorder(root->right); cout<<root->element<<endl; } template<class Elem> void BinaryTree<Elem>::postorder() { postorder(root); } //前序遍历 template<class Elem> void BinaryTree<Elem>::preorder(TreeNode<Elem>*root) { if(root==NULL) return false; cout<<root->element<<endl; inorder(root->left); inorder(root->right); } template<class Elem> void BinaryTree<Elem>::preorder() { preorder(root); } template<class Elem> int BinaryTree<Elem>::getSize() { return size; } template<class Elem> TreeNode<Elem>* BinaryTree<Elem>::inorderFirstLeaf() { if(root==NULL) return NULL; TreeNode<Elem>*temp; temp=root; while(temp->left!=NULL) { temp=temp->left; } if(temp->right==NULL) { return temp; } else return temp->right; } bool isLength() { return 0; } #endif