class Node { public: int data; Node* left; Node* right; }; void pre-order(Node* root) { stack<Node*> stk; if (root) stk.push(root); while (!stk.empty()) { Node* nd = stk.top(); cout << nd->data << endl; stk.pop(); if (nd->right) stk.push(nd->right); if (nd->left) stk.push(nd->left); } } void in-order(Node* root) { stack<Node*> stk; Node* nd = root; while (nd) { stk.push(nd); nd = nd->left; } while (!stk.empty()) { nd = stk.top(); cout << nd->data << endl; stk.pop(); Node* nd2 = nd->right; while (nd2) { stk.push(nd2); nd2 = nd2->left; } } } void post-order(Node* root) { // 使用双队列 stack<Node*> stk1, stk2; if (root) stk1.push(root); while (!stk1.empty()) { Node* nd = stk1.top(); stk1.pop(); stk2.push(nd); if (nd->left) stk1.push(nd->left); if (nd->right) stk1.push(rd->right); } while (!stk2.empty()) { Node* nd = stk2.top(); cout << nd->data << endl; stk2.pop(); } }
时间: 2024-10-12 19:46:52