Preorder
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode *> sta; sta.push(root); while (!sta.empty()) { TreeNode* cur = sta.top(); sta.pop(); res.push_back(cur->val); if (cur->right) sta.push(cur->right); if (cur->left) sta.push(cur->left); } return res; } };
postorder
class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode *> sta; sta.push(root); TreeNode *last = NULL; while (!sta.empty()) { TreeNode *cur = sta.top(); TreeNode *left = cur->left, *right = cur->right; if (left && (!last || (last != left && last != right))) sta.push(left); else if (right && (!last || last != right)) sta.push(right); else { res.push_back(cur->val); last = cur; sta.pop(); } } return res; } };
inorder
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode*> sta; while(1) { while(root) { sta.push(root); root = root->left; } if(sta.empty()) break; root = sta.top(); sta.pop(); res.push_back(root->val); root = root->right; } return res; } };
时间: 2024-12-26 18:12:04