NormalText Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
#include <iostream>
using namespace std; struct tree { int data; tree* left, *right; tree(int num) { data = num; left = NULL; right = NULL; } }; class Btree { static int n; static int m; public: tree* root; Btree(){ root = NULL; } void create_Btree(int x); void PreOrder(tree* temp); void InOrder(tree* temp); void PostOrder(tree* temp); void display1() { PreOrder(root); cout << endl; } void display2() { InOrder(root); cout << endl; } void display3() { PostOrder(root); cout << endl; } int count(tree* temp); int findLeaf(tree* temp); int findNode(tree* temp); }; int Btree::n = 0; int Btree::m = 0; void Btree::create_Btree(int x) { tree* pn = new tree(x); if (!root) { root = pn; return; } tree* back; tree* current = root; while (current) { back = current; if (current->data > x) { current = current->left; } else { current = current->right; } } if (back->data > x) { back->left = pn; } else { back->right = pn; } } void Btree::PreOrder( tree* temp ) { if (temp) { cout << temp->data << " "; PreOrder(temp->left); PreOrder(temp->right); } } void Btree::InOrder( tree* temp ) { if (temp) { InOrder(temp->left); cout << temp->data << " "; InOrder(temp->right); } } void Btree::PostOrder( tree* temp ) { if (temp) { PostOrder(temp->left); PostOrder(temp->right); cout << temp->data << " "; } } int Btree::count( tree* temp ) { if (!temp) { return 0; } return count(temp->left) + count(temp->right) + 1; } int Btree::findLeaf( tree* temp ) { if(!temp) return 0; if(!temp->left && !temp->right) return n += 1; findLeaf(temp->left); findLeaf(temp->right); return n; } int Btree::findNode( tree* temp ) { if(!temp) return 0; if (temp->left && temp->right) { findNode(temp->left); findNode(temp->right); } if (temp->left && !temp->right) { m += 1; findNode(temp->left); } if (!temp->left && temp->right) { m += 1; findNode(temp->right); } return m; } void main( void ) { Btree A; int array[]={7,4,2,3,15,35,6,45,55,20,1,14,56,57,58}; int k; k=sizeof(array)/sizeof(array[0]); cout<<"建立排序二叉树顺序: "<<endl; for(int i=0;i<k;i++) { cout<<array[i]<<" "; A.create_Btree(array[i]); } cout<<endl; cout<<"二叉树节点个数: "<<A.count(A.root)<<endl; cout<<"二叉树叶子个数:"<<A.findLeaf(A.root)<<endl; cout<<"二叉树中度数为1的结点的数量为:"<<A.findNode(A.root)<<endl; cout<<endl<<"先序遍历序列: "<<endl; A.display1(); cout<<endl<<"中序遍历序列: "<<endl; A.display2(); cout<<endl<<"后序遍历序列: "<<endl; A.display3(); } |