1 #ifndef _TREE_H_ 2 #define _TREE_H_ 3 //此类用shared_ptr来管理节点内存,所以要包含<memory>头文件,不需要手动释放内存 4 #include <memory> 5 #include <iostream> 6 7 using namespace std; 8 9 struct Node{ 10 int key; 11 shared_ptr<Node> parent; 12 shared_ptr<Node> left; 13 shared_ptr<Node> right; 14 Node(int k = 0) :key(k), parent(), left(), right() {} 15 }; 16 17 typedef shared_ptr<Node> Pnode; 18 19 class Tree 20 { 21 private: 22 Pnode root; 23 //返回以current为根节点的所有节点个数 24 size_t __nodeSize(Pnode current) const; 25 //返回以current为根节点的叶节点(没有左右节点)个数 26 size_t __leafSize(Pnode current) const; 27 //返回以current为根节点树的深度 28 size_t __depth(Pnode current) const; 29 //返回k值节点的地址 30 const Pnode * __getNodeAddress(int k) const; 31 //返回current节点下的最大值的节点 32 Pnode __maxNode(Pnode current) const; 33 //返回current节点下的最小值节点 34 Pnode __minNode(Pnode current) const; 35 void showNode(Pnode current) const; 36 public: 37 Tree() :root() {} 38 //将k插入树 39 void insert(int k); 40 //删除值为k的节点 41 void delNode(int k); 42 //判断是否存在值为k的节点 43 bool isExist(int k); 44 //树中节点个数 45 size_t nodeSize() const; 46 //树中叶节点的个数 47 size_t leafSize() const; 48 //树的深度 49 size_t depth() const; 50 //树的宽度 51 size_t width() const; 52 //树的最大值 53 int maxVal() const; 54 //树的最小值 55 int minVal() const; 56 //打印所有节点 57 void showAll() const; 58 }; 59 60 61 #endif
相关文章: