二叉树程序上removeAll与remove这俩函数的作用,该如何处理
二叉树程序上removeAll与remove这俩函数的作用
------解决方案--------------------
- C/C++ code
#include <iostream> #include <iomanip> using namespace std; typedef int T; struct Node{ T data; Node* left; Node* right; Node(const T& d):data(d),left(),right(){} }; class Bst{ private: Node* root; int sz; typedef Node* tree; void insert(Node*p,tree&t) { if(p==NULL) return; if(t==NULL) t=p; else if(p->data>t->data) insert(p,t->right); else insert(p,t->left); } void travel(tree&t) { if(t==NULL) return; travel(t->left); cout << t->data <<' '; travel(t->right); } void clear(tree&t) { if(t==NULL) return; clear(t->left); clear(t->right); delete t; } tree& find(const T&d,tree&t) { if(t==NULL) return t; if(t->data==d) return t; if(d>t->data) return find(d,t->right); return find(d,t->left); } int high(tree& t) { if(t==NULL) return 0; int lh = high(t->left); int rh = high(t->right); return (lh>rh?lh:rh)+1; } void print(tree&t,int s,char c) { if(t==NULL) return; print(t->right,s+3,'/'); cout << setw(s) << c << t->data <<endl; print(t->left,s+3,'\\'); } public: Bst():root(),sz(){} ~Bst() {clear();} void insert(const T& d) { Node* pn = new Node(d); insert(pn,root); sz++; } void travel() { travel(root); cout<<endl; } void clear() { clear(root); root=NULL; sz=0; } tree& find(const T& d) { return find(d,root); } bool remove(const T& d)//这个函数的作用 { tree& t = find(d); if(t==NULL) return false; insert(t->left,t->right); Node* p =t; t = t->right; delete p; sz--; return true; } void removeAll(const T& d)//这个函数的作用 { while(remoove(d)); } void modify(const T& old,const T& newVal) { while(remove(old)) insert(newVal); } int high() { return high(root); } void print() { print(root,0,'*'); } int size() { return sz; } }; int main() { Bst t; t.insert(5); t.insert(3); t.insert(2); t.insert(4); t.insert(8); t.insert(6); t.insert(9); cout << t.high() <<endl; t.print(); cout<<"size="<<t.size()<<endl; }
------解决方案--------------------
- C/C++ code
int high(tree& t) { if(t == NULL) return 0; int lh = high(t->left); int rh = high(t->right); //+1这个猜测是返回最高值的上层 return (lh > rh ? lh : rh) + 1; } void print(tree&t,int s,char c) { if(t == NULL) return; //print函数输出整棵树, 而参数int s表示输出的字符间隔 //s + 3表示输出的字符间隔 + 3, 可以让输出的数据更清晰 print(t->right, s + 3, '/'); cout << setw(s) << c << t->data <<endl; print(t->left, s + 3, '\\'); }
------解决方案--------------------
要分析一个函数的功能的话,看看与它相关的函数。
- C/C++ code
int high(tree& t) { if(t==NULL) return 0; int lh = high(t->left); int rh = high(t->right); return (lh>rh?lh:rh)+1;//+1什么效果? }