迭代法 二叉树前序、中序、后序 遍历
前序
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> res; if (root == nullptr) { return res; } stack<TreeNode*> stk; TreeNode* node = root; while (!stk.empty() || node != nullptr) { while (node != nullptr) { res.emplace_back(node->val); stk.emplace(node); node = node->left; } node = stk.top(); stk.pop(); node = node->right; } return res; } };
中序
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode*> stk; while (root != nullptr || !stk.empty()) { while (root != nullptr) { stk.push(root); root = root->left; } root = stk.top(); stk.pop(); res.push_back(root->val); root = root->right; } return res; } };
后序
class Solution { public: vector<int> postorderTraversal(TreeNode *root) { vector<int> res; if (root == nullptr) { return res; } stack<TreeNode *> stk; TreeNode *prev = nullptr; while (root != nullptr || !stk.empty()) { while (root != nullptr) { stk.emplace(root); root = root->left; } root = stk.top(); stk.pop(); //如果当前节点的右子树为空,或者已经在上一次访问过,则访问当前节点 if (root->right == nullptr || root->right == prev) { res.emplace_back(root->val); prev = root; root = nullptr; } else { stk.emplace(root); root = root->right; } } return res; } };