栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

天梯练习:树的遍历

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

天梯练习:树的遍历

思路分析:

  这道题主要就是根据后序和中序遍历进行建树。

  (1)定义一个树的结构体,结构体成员包含当前节点的左儿子和右儿子。

  (2)定义一个建树的函数,由于后序遍历的最后一位是当前数的根节点,所以在中序遍历中找到根节点的位置,然后分为左右子树继续递归。最后返回整个树的根节点。

  (3)定义一个层序遍历的函数,传入的是根节点,然后根据队列的方式每次都是先放左儿子再放右儿子。

代码实现:

#include
using namespace std;
struct node
{
    int l;
    int r;
}tree[10010];
int zhong[10010],hou[10010];
queueq;
int n;
int buildtree(int left,int right,int begin,int end)
{      if(left>right||begin>end)
          return -1;
      int root=hou[right];
      int p;
      for(int i=begin;i<=end;i++)
         if(zhong[i]==root)
           {
                p=i;
                break;
           }
       int sx=p-begin;
       int sy=end-p;
       tree[root].l=buildtree(left,left+sx-1,begin,begin+sx-1);
       tree[root].r=buildtree(right-sy,right-1,end-sy+1,end);
      return root;
}
void ceng(int root)
{   int num;
    q.push(root);
    while(!q.empty())
    {
        num=q.front();
        q.pop();
        if(tree[num].l!=-1)
        {
            q.push(tree[num].l);
        }
        if(tree[num].r!=-1)
        {
            q.push(tree[num].r);
        }
        if(num==root)
          cout<>n;
    for(int i=0;i>hou[i];

     for(int i=0;i>zhong[i];

    struct node k;
 
    int root;
    root=buildtree(0,n-1,0,n-1);
     ceng(root);
    return 0;
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/779154.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号