二叉树的先序非递归实现
思路:用栈模拟先序过程,先序是先根节点,后左节点,后右节点
void preOrderWithoutRecusive(TreeNode* root)
{
if (root == nullptr)
return;
stack<TreeNode*>sta;
TreeNode* tmp = root;
while (!sta.empty() || tmp)
{
if (tmp)
{
cout << tmp->val << " ";
sta.push(tmp);
tmp = tmp->left;
}
else
{
tmp = sta.top();
sta.pop();
tmp = tmp->right;
}
}
}
二叉树的中序非递归实现
void inOrderWithoutRecusive(TreeNode* root)
{
if (root == nullptr)
return;
stack<TreeNode*>sta;
TreeNode* tmp = root;
while (!sta.empty() || tmp)
{
if (tmp)
{
sta.push(tmp);
tmp = tmp->left;
}
else
{
tmp = sta.top();
sta.pop();
cout << tmp->val << " ";
tmp = tmp->right;
}
}
}
二叉树的后序非递归实现
思路: 双栈法,一个栈模拟修改的先序遍历(根-右-左),另一个栈逆向输出(左-右-根)
void PostOrderWithoutRecusive(TreeNode *root)
{
if (root == nullptr)
{
return;
}
stack<TreeNode *>sta1;
stack<TreeNode *>sta2;
TreeNode * tmp = root;
while (!sta1.empty() || tmp)
{
if (tmp)
{
sta1.push(tmp);
sta2.push(tmp);
tmp = tmp->right;
}
else
{
tmp = sta1.top();
sta1.pop();
tmp = tmp->left;
}
}
while (!sta2.empty())
{
cout<<sta2.top()<<" ";
sta2.pop();
}
}