学习笔记——二叉树的遍历

一、先序遍历的实现及其性质

对于二叉树的先序遍历序列,序列的第一个一定是根结点。

void preorder(node* root)
{
    if(root==NULL) return;
    cout<<root->data;
    preorder(root->lchild);
    preorder(root->rchild);
}

二、中序遍历的实现及其性质

根结点总是位于左子树和右子树中间的位置,所以只要知道根结点,就可以通过根结点在中序遍历序列中的位置区分出左子树和右子树。

void inorder(node* root)
{
    if(root==NULL) return;
    inorder(root->lchild;
    cout<<root->data;
    inorder(root->rchild;
}

三、后序遍历的实现及其性质

后序序列的最后一个位置一定是根结点。

void postorder(node* root)
{
    if(root==NULL) return;
    postorder(root->lchild);
    postorder(root->rchild);
    cout<<root->data;
}

四、层序遍历

//记录层次的层序遍历代码

struct node{
    int data;
    int layer;
    node* lchild;
    node* rchild;
};

void layerorder(node* root)
{
    queue<node*> q;
    root->layer=1;
    q.push(root);
    while(!q.empty())
    {
        node* now=q.front();
        q.pop();
        cout<<now->data;
        if(now->lchild!=NULL)
        {
            now->lchild->layer=now->layer+1;
            q.push(now->lchild);
        }
        if(now->rchild!=NULL)
        {
            now->rchild->layer=now->layer+1;
            q.push(now->rchild);
        }
    }
}

五、给定一棵二叉树的先序遍历序列和中序遍历序列重建二叉树的思想以及实现代码

node* create(int prel,int prer,int inl,int inr)
{
	if(prel>prer)
		return NULL;
	node* root=new node;
	root->data=pre[prel];
	int k;
	for(k=inl;k<=inr;k++)
	{
		if(in[k]==pre[prel])
			break;
	}
	int numleft=k-inl;
	root->lchild=create(prel+1,prel+numleft,inl,k-1);
	root->rchild=create(prel+numleft+1,prer,k+1,inr);
	return root;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.无名之辈

1毛也是爱~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值