day14
用栈来模拟
前序遍历:中左右
所以一开始就处理中间的,将它加入数组中。
随后将 右 左 分别放入栈中
一定是先 右 后 左,因为栈是后入先出的。弹出之后才是中左右的顺序。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> 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) st.push(node->right); // 一定要注意这里的顺序
if(node->left) st.push(node->left);
}
return res;
}
};
后序遍历是
左右中
在前序遍历中,如果左右颠倒,再将数组反转
得到的就是左右中
颠倒后:中右左
反转:左右中
代码如下:
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> 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) st.push(node->left); // 颠倒
if(node->right) st.push(node->right);
}
// 反转
reverse(res.begin(),res.end());
return res;
}
};