前序遍历144
思路:栈是先进后出的,前序遍历是中左右;因此入队时先入右再入左
class Solution {public:vector<int> preorderTraversal(TreeNode* root) {vector<int> res;if (root == nullptr) return res;stack<TreeNode*> st;st.push(root);while (!st.empty()) {int len = st.size();for (int i = 0; i < len; ++i) {TreeNode* node = st.top(); st.pop();res.push_back(node->val);if (node->right) st.push(node->right);if (node->left) st.push(node->left);}}return res;}};
中序遍历94
- 思路:左中右;先走到最左边,然后操作,然后往右走
注意:该遍历比较反常规,需要好好看一下
class Solution {public:vector<int> inorderTraversal(TreeNode* root) {vector<int> res;if (root == nullptr) return res;stack<TreeNode*> st;TreeNode* cur = root;while (cur != nullptr || !st.empty()) {if (cur != nullptr) {st.push(cur);cur = cur->left; // 左}else {cur = st.top(); st.pop();res.push_back(cur->val); // 中cur = cur->right; // 右}}return res;}};
后序遍历145
思路:后序遍历是左右中;操作后,先入队左,再入队右,最后对整个数组进行翻转
class Solution {public:vector<int> postorderTraversal(TreeNode* root) {vector<int> res;if (root == nullptr) return res;stack<TreeNode*> st;st.push(root);while (!st.empty()) {int len = st.size();for (int i = 0; i < len; i++) {TreeNode* node = st.top(); st.pop();res.push_back(node->val);if (node->left) st.push(node->left);if (node->right) st.push(node->right);}}reverse(res.begin(), res.end());return res;}};
