用顯式棧模擬遞歸調用棧。前序、中序、後序只需調整入棧順序與輸出時機。
vector preorder(TreeNode* root) {
vector res;
stack st;
if (root) st.push(root);
while (!st.empty()) {
TreeNode* n = st.top(); st.pop();
res.push_back(n->val);
if (n->right) st.push(n->right);
if (n->left) st.push(n->left);
}
return res;
}
vector inorder(TreeNode* root) {
vector res;
stack st;
TreeNode* cur = root;
while (cur || !st.empty()) {
while (cur) { st.push(cur); cur = cur->left; }
cur = st.top(); st.pop();
res.push_back(cur->val);
cur = cur->right;
}
return res;
}
vector postorder(TreeNode* root) {
vector res;
stack st;
if (root) st.push(root);
while (!st.empty()) {
TreeNode* n = st.top(); st.pop();
res.push_back(n->val);
if (n->left) st.push(n->left);
if (n->right) st.push(n->right);
}
reverse(res.begin(), res.end()); // 反轉得後序
return res;
}