标签:
搞了两天终于把中序遍历弄到类里面来了
比在类外调用爽了一点。
在n个节点的情况下,中序遍历多出一个if的时间复杂度为O(n)+O(1),最后还是O(n),哈哈。
class BSTree { private: struct TreeNode { int key; TreeNode *p, *left, *right; }; TreeNode *root; short i; public: BSTree():root(nullptr),i(0){} void Insert(int k); /*TreeNode *getRoot(){ return root; } 返回root节点用于做类外中序遍历的参数*/ void InorderTreeWalk(TreeNode *n = nullptr); }; //插入 void BSTree::Insert(int k) { TreeNode *z = new TreeNode(); z->key = k; z->left = nullptr; z->right = nullptr; TreeNode *y = nullptr, *x = this->root; while (x) { y = x; if (z->key < x->key) x = x->left; else x = x->right; } z->p = y; if (!y) this->root = z; else if (z->key < y->key) y->left = z; else y->right = z; } //中序遍历 void BSTree::InorderTreeWalk(TreeNode *n) { //初始化n,设置记录 if (i == 0 && !n) { n = this->root; i++; } if (n) { InorderTreeWalk(n->left); cout << n->key << " "; InorderTreeWalk(n->right); } }
标签:
原文地址:http://www.cnblogs.com/doublelovelymo/p/4383846.html