二叉树的前序非递归遍历
思路:对每个结点按照 根->右->左 的顺序入栈,出栈的顺序就是前序遍历的结果。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if(!root)
return vector<int>();
vector<int> res;
stack<TreeNode*> sta;
sta.push(root);
while(!sta.empty())
{
TreeNode* head = sta.top();
sta.pop();
res.push_back(head->val);
if(head->right)
sta.push(head->right);
if(head->left)
sta.push(head->left);
}
return res;
}
};
二叉树的中序遍历非递归
思路:
(1)树先一直向左走到叶节点并将沿途的结点入栈 ;
(2)然后向右走一步,重复第一步操作。
注意要将沿途的节点进行入栈
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> sta;
TreeNode* head = root;
while(head || !sta.empty())
{
while(head)
{
sta.push(head);
head = head->left;
}
head = sta.top();
res.push_back(head->val);
sta.pop();
head = head->right;
}
return res;
}
};
二叉树的非递归后序遍历
利用栈实现,先按照 中->左->右的顺序遍历树并放入栈中(方法类似前序遍历中->左->右),然后将栈的数据转移到另一个栈中,遍历顺序就变成 左->右->中(后序顺序)
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
if(!root)
return vector<int>();
vector<int> res;
stack<TreeNode*> sta1,sta2;
sta1.push(root);
while(!sta1.empty())
{
TreeNode* cur = sta1.top();
sta1.pop();
sta2.push(cur);//注意这里的写法这样st2存储的顺序变成了根-右-左
if(cur->left)
sta1.push(cur->left);
if(cur->right)
sta1.push(cur->right);
}
while(!sta2.empty())
{
TreeNode* cur = sta2.top();
sta2.pop();
res.push_back(cur->val);
}
return res;
}
};