前序遍历是中左右,每次先处理的是中间节点,那么先将根节点放入栈中,然后将右孩子加入栈,再加入左孩子。
为什么要先加入 右孩子,再加入左孩子呢? 因为这样出栈的时候才是中左右的顺序。
144. 二叉树的前序遍历
class Solution {
public:
vector preorderTraversal(TreeNode* root) {
stack st; // 用来存储节点
vector res; // 返回值
if (root == nullptr) {
return res;
}
// 把根加入到栈中
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
res.push_back(node->val); // 处理根节点
if (node->right != nullptr) { // 右子树
st.push(node->right);
}
if (node->left != nullptr) { // 左子树
st.push(node->left);
}
}
return res;
}
};
2、中序遍历
分析一下为什么刚刚写的前序遍历的代码,不能和中序遍历通用呢,因为前序遍历的顺序是中左右,先访问的元素是中间节点,要处理的元素也是中间节点,所以刚刚才能写出相对简洁的代码,因为要访问的元素和要处理的元素顺序是一致的,都是中间节点。
那么再看看中序遍历,中序遍历是左中右,先访问的是二叉树顶部的节点,然后一层一层向下访问,直到到达树左面的最底部,再开始处理节点(也就是在把节点的数值放进result数组中),这就造成了处理顺序和访问顺序是不一致的。
那么在使用迭代法写中序遍历,就需要借用指针的遍历来帮助访问节点,栈则用来处理节点上的元素。
94. 二叉树的中序遍历
class Solution {
public:
vector inorderTraversal(TreeNode* root) {
stack st;
vector res;
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;
}
};
3、后序遍历
再来看后序遍历,先序遍历是中左右,后续遍历是左右中,那么我们只需要调整一下先序遍历的代码顺序,就变成中右左的遍历顺序,然后在反转result数组,输出的结果顺序就是左右中了。
145. 二叉树的后序遍历
class Solution {
public:
vector postorderTraversal(TreeNode* root) {
stack st;
vector res;
if (root == nullptr) {
return res;
}
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
res.push_back(node->val); // 根
if (node->left != nullptr) { // 左
st.push(node->left);
}
if (node->right != nullptr) { // 右
st.push(node->right);
}
}
reverse(res.begin(), res.end()); // 反转
return res;
}
}; 


