//-----二叉树
struct treeNode
{
int data;
struct treeNode*left;
struct treeNode *right;
};
void createTree(treeNode *&root)
{
treeNode *t = (treeNode *)malloc(sizeof(treeNode));
t->left = NULL;
t->right = NULL;
t->data = 5;
root = t;
treeNode *t1 = (treeNode *)malloc(sizeof(treeNode));
t1->left = NULL;
t1->right = NULL;
t1->data = 3;
root->left = t1;
treeNode *t2 = (treeNode *)malloc(sizeof(treeNode));
t2->left = NULL;
t2->right = NULL;
t2->data = 1;
root->right = t2;
treeNode *t3 = (treeNode *)malloc(sizeof(treeNode));
t3->left = NULL;
t3->right = NULL;
t3->data = 2;
root->left->right = t3;
treeNode *t4 = (treeNode *)malloc(sizeof(treeNode));
t4->left = NULL;
t4->right = NULL;
t4->data = 4;
root->right->right = t4;
treeNode *t5 = (treeNode *)malloc(sizeof(treeNode));
t5->left = NULL;
t5->right = NULL;
t5->data = 7;
root->left->right->left = t5;
treeNode *t6 = (treeNode *)malloc(sizeof(treeNode));
t6->left = NULL;
t6->right = NULL;
t6->data = 9;
root->left->right->right = t6;
}
//树递归先序遍历
void preOrder(treeNode *root){
if (root != NULL)
{
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
}
//现将根节点入栈,然后以栈空为条件不断出栈,
//每出栈一个元素,将其右孩子压入栈,左孩子压入栈
void nonRecursionPreorder(treeNode*r)
{
treeNode*p = r;
stack < treeNode*>s;
s.push(p);
while (!s.empty())
{
treeNode*t = s.top();
s.pop();
cout << t->data << " ";
if (t->right) s.push(t->right);
if (t->left) s.push(t->left);
}
cout << endl;
}
//--递归中序遍历
void inOrder(treeNode*root)
{
if (root != NULL)
{
inOrder(root->left);
cout << root->data << " ";
inOrder(root->right);
}
}
//用一个指针标记当前访问的节点(初始为根节点),如果栈为空且当前指针为空说明遍历结束;
//在遍历过程中将当前节点开始一直向左都押入栈中,
//然后取出栈顶元素,并将当前指针设为右孩子
void nonRecursionInorder(treeNode*r)
{
treeNode*p = r;//当前节点的指针
stack < treeNode*>s;
while (p != NULL || !s.empty())
{
while (p)//将最左侧的节点都押入栈中
{
s.push(p);
p = p->left;
}
treeNode*temp = s.top();
cout << temp->data << " ";
s.pop();
p = temp->right;
}
cout << endl;
}
//递归后序遍历
void postOrder(treeNode*root)
{
if (root != NULL)
{
postOrder(root->left);
postOrder(root->right);
cout << root->data << " ";
}
}
void nonRecursionPostorder(treeNode*r)
{
treeNode *p = r;
treeNode *lastedVisted = NULL;
stack<treeNode*>s;
while (p || !s.empty())//遍历树的结束条件
{
while (p)
{
s.push(p);
p = p->left;
}
treeNode* temp = s.top();
if (temp->right == NULL || lastedVisted == temp->right)//说明访问到了根节点
{
s.pop();
cout << temp->data << " ";
lastedVisted = temp;
}
else
{
p = temp->right;
}
}
cout << endl;
}