#include <iostream> using namespace std; struct Tree { int data; Tree *left; Tree *right; }; class BinaryTree { public: Tree *root; // 根节点 int hight; // 整颗树的高度 BinaryTree() { this->root = NULL; hight = 0; } void create_BinaryTree(int); // 创建一个二叉搜索树 void pre_travel_BinaryTree(Tree *); // 遍历二叉搜索树 int node_count(Tree *); // 统计二叉搜索树一共有多少个节点 void hight_BinaryTree(Tree *, int); }; void BinaryTree::create_BinaryTree(int data) { Tree *newnode = new Tree; newnode->data = data; newnode->left = newnode->right = NULL; if (this->root == NULL) this->root = newnode; else { Tree *back; Tree *current = this->root; while (current != NULL) { back = current; if (current->data > data) current = current->left; else current = current->right; } if (back->data > data) back->left = newnode; else back->right = newnode; } } void BinaryTree::pre_travel_BinaryTree(Tree *tree) { if (tree != NULL) { this->pre_travel_BinaryTree(tree->left); cout << tree->data << " "; this->pre_travel_BinaryTree(tree->right); } } int BinaryTree::node_count(Tree *tree) { if (tree == NULL) return 0; else return this->node_count(tree->left) + this->node_count(tree->right) + 1; } void BinaryTree::hight_BinaryTree(Tree *tree, int temp_hight) { if (tree == NULL) { if (temp_hight > this->hight) this->hight = temp_hight; } else { this->hight_BinaryTree(tree->left, temp_hight + 1); this->hight_BinaryTree(tree->right, temp_hight + 1); } } int main() { BinaryTree *binary_tree = new BinaryTree(); // 创建一颗二叉搜索树 int array[] = { 7,4,2,3,15,35,6,45,55,20,1,14,56,57,58 }; int array_length = sizeof(array) / sizeof(array[0]); for (int i = 0; i < array_length; i++) binary_tree->create_BinaryTree(array[i]); // 遍历二叉搜索树 binary_tree->pre_travel_BinaryTree(binary_tree->root); cout << endl; // 统计二叉搜索树一共有多少个节点 cout << binary_tree->node_count(binary_tree->root) << endl; // 统计二叉搜索树的高度 binary_tree->hight_BinaryTree(binary_tree->root, 0); cout << binary_tree->hight << endl; system("pause"); return 0; }
参考链接:http://www.cnblogs.com/elleniou/archive/2012/05/03/2480042.html