标签:void oid for ++ 二叉排序树 val col break tree
二叉排序树的创建
首先定义树节点treeNode:包含节点的值value 以及其左右孩子指针left right
1 class treeNode 2 { 3 public: 4 int value; 5 treeNode *right,*left; 6 treeNode():right(NULL),left(NULL){} 7 };
定义二叉排序树Tree:包含根节点Root,节点个数num,以及构造函数(创建树)、中序遍历(输出排序结果)、插入和删除函数
1 class Tree 2 { 3 private: 4 treeNode *Root;//根节点 5 int num; //节点个数 6 void inOrder(treeNode *p); 7 public: 8 Tree(int d[], int n); 9 void inOrder(); 10 void insert(int v); 11 }; 12 Tree::Tree(int a[], int n) 13 { 14 num = n; 15 Root = new treeNode(); 16 Root->value = a[0]; 17 for (int i = 1; i < num; i++) 18 { 19 treeNode *p = Root; 20 while (true) 21 { 22 if (a[i] > p->value) 23 { 24 if (!p->right) //p的右子树为空 那就插到右子树去 25 { 26 treeNode *q = new treeNode(); 27 q->value = a[i]; 28 p->right = q; 29 break; 30 } 31 p = p->right; 32 } 33 else if (a[i] < p->value) 34 { 35 if (!p->left) 36 { 37 treeNode *q = new treeNode(); 38 q->value = a[i]; 39 p->left = q; 40 break; 41 } 42 p = p->left; 43 } 44 } 45 } 46 } 47 48 void Tree::inOrder() 49 { 50 inOrder(Root); 51 cout << endl; 52 } 53 54 void Tree::inOrder(treeNode *p) 55 { 56 if (p) 57 { 58 inOrder(p->left); 59 cout << p->value << " "; 60 inOrder(p->right); 61 } 62 } 63 64 void Tree::insert(int v) 65 { 66 treeNode *p = Root; 67 while (true) 68 { 69 if (v > p->value) 70 { 71 if (!p->right) //p的右子树为空 那就插到右子树去 72 { 73 treeNode *q = new treeNode(); 74 q->value = v; 75 p->right = q; 76 break; 77 } 78 p = p->right; 79 } 80 else if (v < p->value) 81 { 82 if (!p->left) 83 { 84 treeNode *q = new treeNode(); 85 q->value = v; 86 p->left = q; 87 break; 88 } 89 p = p->left; 90 } 91 92 } 93 }
标签:void oid for ++ 二叉排序树 val col break tree
原文地址:https://www.cnblogs.com/Liu269393/p/10212528.html