二叉搜索树的建立, 查找, 删除操作...

#include <cstdlib> #include <iostream> using namespace std; typedef struct _NODE { int value; struct _NODE *left; struct _NODE *right; _NODE(int value) : value(value), left(NULL), right(NULL) {}; }NODE, *PTRNODE; void insert(PTRNODE &root, int value) { if(root == NULL) root = new NODE(value); else { if(value < root->value) insert(root->left, value); else if(value > root->value) insert(root->right, value); else cout << “duplicated value” << endl; } } void preOrder(PTRNODE root) { if(root != NULL) { cout << root->value << “->”; preOrder(root->left); preOrder(root->right); } } void inOrder(PTRNODE root) { if(root != NULL) { inOrder(root->left); cout << root->value << “->”; inOrder(root->right); } } void postOrder(PTRNODE root) { if(root != NULL) { inOrder(root->left); inOrder(root->right); cout << root->value << “->”; } } void clear(PTRNODE &root) { if(root != NULL) { clear(root->left); clear(root->right); delete root; root = NULL; } } void _search(PTRNODE root, int searchVal) { if(root == NULL) { cout << “not find… ” << endl; return; } if(searchVal < root->value) _search(root->left, searchVal); else if(searchVal > root->value) _search(root->right, searchVal); else cout << “find… ” << endl; } int main(int argc, char *argv[]) { PTRNODE root = NULL; cout << “init is: ” << endl; for(int i=0; i<10; i++) { int value = rand() % 100; cout << value << ” “; insert(root, value); } cout << endl; cout << “pre order result is: ” << endl; preOrder(root); cout << endl; cout << “in order result is: ” << endl; inOrder(root); cout << endl; cout << “post order result is: ” << endl; postOrder(root); cout << endl; cout << “please input a search value: “; int searchVal; cin >> searchVal; _search(root, searchVal); clear(root); system(“PAUSE”); return EXIT_SUCCESS; }  

 

计算二叉树节点数量和高度的实现如下:

 

 

int getSize(PTRNODE root) { if(root == NULL) return 0; return 1 + getSize(root->left) + getSize(root->right); } int getHeight(PTRNODE root) { if(root == NULL) return -1; return 1 + max(getHeight(root->left), getHeight(root->right)); } 

 

二叉树的拷贝和比较实现如下:

 

PTRNODE copy(const PTRNODE root) { if(root == NULL) return NULL; PTRNODE temp = new NODE(0); temp->value = root->value; temp->left = copy(root->left); temp->right = copy(root->right); return temp; } bool isEqual(const PTRNODE tree1, const PTRNODE tree2) { if(tree1 == NULL && tree2 == NULL) return true; if(tree1 != NULL && tree2 != NULL && tree1->value == tree2->value && isEqual(tree1->left, tree2->left) && isEqual(tree1->right, tree2->right)) return true; return false; } 

 

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/CNnumen/article/details/5727328
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞