标签:code nbsp 后序 pos 二叉树 treenode color 参考 turn
前序
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; } };
标签:code nbsp 后序 pos 二叉树 treenode color 参考 turn
原文地址:https://www.cnblogs.com/0patrick/p/14200994.html