核心提示:二叉树遍历代码实例//前序遍历:根节点-左子树-右子树//中序遍历:左子树-根节点-右子树//后序遍历:左子树-右子树-根节点//定义数据类型可以用泛型struct Data{int hp;};//树...
二叉树遍历代码实例
//前序遍历:根节点->左子树->右子树 //中序遍历:左子树->根节点->右子树 //后序遍历:左子树->右子树->根节点 //定义数据类型可以用泛型 struct Data { int hp; }; //树的节点 struct Node { Data data; Node* left; Node* right; Node(int num):left(NULL),right(NULL){} Node(){} }; class Tree { public: Tree():root(NULL),len(0){} ~Tree(){} Node* root; void addNode(int num); void qian(); void digui_qian(Node* node); void zhong(); void digui_zhong(Node* node); void hou(); void digui_hou(Node* node); void ceng(); private: int len; vectorm_vec; }; //创建 void addNode(int num) { len++; int n = len; Noed* node = new Node(num); if(n == 1) { root = node; } else { n = n/2; if(len%2) { m_vec[n-1]->right = node; } else { m_vec[n-1]->left = node; } } m_vec.push_back(node); } //前序遍历:根节点->左子树->右子树 //非递归 void qian() { Node* node = root; stack sta; while(node || sta.size()) { if(node) { cout << node->data.hp << endl; if(node->right) sta.push(node->right) node = node->left; } else { node = sta.top(); sta.pop(); } } } //递归 void digui_qian(Node* node) { if(node) { cout << node->date.hp < left); digui_xian(node->right); } } //中序遍历:左子树->根节点->右子树 //非递归 void zhong() { Node* node = root; stack sta; if(node || sta.size()) { if(node) { sta.push(node); node = node->left; } else { node = sta.top(); sta.pop(); cout << node->data.hp < right; } } } //递归 void digui_zhong(Node* node) { if(node) { digui_xian(node->left); cout << node->date.hp < right); } } //后序遍历:左子树->右子树->根节点 //非递归 void hou() { Node* node = root; Stack sta; while(node || sta.size()) { if(node) { sta.push(node); node = node->left; } else { node = node->right; if(node) continue; node = sta.top(); sta.pop(); cout << node->data.hp << endl; while(sta.size() && sta.top()->right == node) { node = sta.top(); sta.pop(); cout << node->data.hp < right; else return; } } } //后序遍历:左子树->右子树->根节点 //递归 void digui_hou(Node* node) { if(node) { digui(node->left); digui(node->right); cout << node->data.hp < que; que.push (root); while(que.size()) { temp=que.front(); que.pop(); cout< data.hp< left ) que.push( temp->left ); if ( temp->right ) que.push( temp->right ); } }