二叉树的各种遍历

//-----二叉树
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值