先壓棧的是右孩子,再是左孩子,因爲棧先進後出的特色,先取出來的就是左孩子,而後是右孩子,知足 根 - 左 - 右
。post
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode*> s; s.push(root); TreeNode *node; while (!s.empty()) { node = s.top(); s.pop(); res.push_back(node->val); if (node->right) s.push(node->right); if (node->left) s.push(node->left); } return res; } };
直接模擬中序遍歷的過程。leetcode
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; if (!root) return res; TreeNode *node = root; stack<TreeNode*> s; while (!s.empty() || node) { if (node) { s.push(node); node = node->left; } else { node = s.top(); s.pop(); res.push_back(node->val); node = node->right; } } return res; } };
有點抽象,總之只需理解 根 - 右 - 左
逆過來就是 左 - 右 - 根
。io
class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode*> s; s.push(root); TreeNode *node; while (!s.empty()) { node = s.top(); s.pop(); res.push_back(node->val); if (node->left) s.push(node->left); if (node->right) s.push(node->right); } reverse(res.begin(), res.end()); return res; } };