排序二叉樹的c++實現
阿新 • • 發佈:2019-01-09
class tree { public: tree(); ~tree(); datatype info; tree *lchild; tree *rchild; private: }; tree::tree() { rchild = NULL; lchild = NULL; } tree::~tree() { } class treelink { public: treelink(); ~treelink(); void add(datatype x); void display(); void display(tree *t); tree *root; private: }; treelink::treelink() { root = new tree(); } treelink::~treelink() { } void treelink::add(datatype x) { if (root == NULL) { root->info = x; cout << "root succ" << endl; } else { tree *temp = root, *p; p = new tree(); int succee = 0;//判斷是否新增成功 while (succee == 0) { if (x.price <= temp->info.price)//小 { if (temp->lchild == NULL)//root左孩子為空 { p->info = x; p->lchild = NULL; p->rchild = NULL; temp->lchild = p; succee = 1; } else { temp = temp->lchild; } } else { if (temp->rchild == NULL)//root右孩子為空 { p->info = x; p->lchild = NULL; p->rchild = NULL; temp->rchild = p; succee = 1; } else { temp = temp->rchild; } } } } } void treelink::display() { tree *temp = root; } void treelink::display(tree *t) { if (t) { display(t->lchild); t->info.display(); cout << " "; display(t->rchild); } }