针对之前写的那个前序遍历,修改了一下。思路和按层遍历是一样的(看别人的文章获悉这两个遍历思路一样,写完代码才发现,的确一样)
因为顺序是根---->右孩子---->左孩子,所以,先输出(或者是其他的处理)根,然后将右孩子和左孩子分别入栈,每次出栈的节点只有一个,所以出栈之后的节点再将它的右孩子左孩子分别入栈。。。(就是递归版本的运行时栈情况)
#include <iostream>
#include <stack>
using namespace std;
struct BSTNode
{
int value;
BSTNode* left;
BSTNode* right;
BSTNode()
{
value = 0;
left = NULL;
right = NULL;
}
};
stack<BSTNode*> st;
void insert(BSTNode* &p, int elem)
{
if(p == NULL)
{
BSTNode* pnew = new BSTNode();
pnew->left = 0;
pnew->right =0;
pnew->value = elem;
p = pnew;
return;
}
if(elem > p->value)
{
insert(p->right, elem);
}
else if(elem < p->value)
{
insert(p->left, elem);
}
else
cout << "The Same!" << endl;
}
void preorder(BSTNode* root)
{
BSTNode* p = root;
st.push(p);
while(!st.empty())
{
p = st.top();
st.pop();
cout << p->value << endl;
if(p->right)
{
st.push(p->right);
}
if(p->left)
{
st.push(p->left);
}
}
}
int main(void)
{
BSTNode* root = 0;
insert(root, 8);
insert(root, 6);
insert(root, 10);
insert(root, 5);
insert(root, 7);
insert(root, 9);
insert(root, 11);
insert(root, 12);
insert(root, 4);
insert(root, 3);
insert(root, 14);
preorder(root);
return 0;
}
本文介绍了一种改进的前序遍历算法实现,通过调整遍历顺序使其与层序遍历保持一致,实现效率优化。具体步骤包括初始化栈、插入节点、遍历节点及其子节点,并展示了一个具体的实例。
5728

被折叠的 条评论
为什么被折叠?



