zoukankan      html  css  js  c++  java
  • 按层次遍历二叉树

    题目描述:

    从上往下打印出二叉树的每个节点,同层节点从左至右打印。

    思路:

    根结点入队,然后循环判断队列是否为空,不为空则出队列,然后判断出队列的结点是否含有左右子结点,有的话则左右子结点分别进队列,直到队列为空

    实现代码如下:

    #include<iostream> 
    #include<queue>
    using namespace std; 
    struct treenode 
    { 
         char data; 
         treenode *lchild; 
         treenode *rchild; 
    }; 
     //先序创建二叉树 
    treenode *init() 
    { 
         char data; 
         cout<<"please inpur a number:(#代表NULL)"<<endl; 
         cin>>data; 
         if(data=='#') 
             return NULL; 
         treenode *head=new treenode; 
         head->data=data; 
         head->lchild=init(); 
         head->rchild=init(); 
         return head; 
    }
    //按层次打印二叉树
    void print(treenode *head)
    {
        queue<treenode *>myque;
        if(head)
        {
            myque.push(head);
        }
        while(!myque.empty())
        {
            //获得队列头的数据并打印
            treenode *temp=myque.front();
            cout<<temp->data<<"    ";
            myque.pop();
            if(temp->lchild)
                myque.push(temp->lchild);
            if(temp->rchild)
                myque.push(temp->rchild);
    }     }

    测试代码以及运行结果:

    int main()
    {
        treenode *head=init();
        print(head);
        return 0;
    }

  • 相关阅读:
    perl 获取铜板街页码
    $response->decoded_content 和$response->content
    基于Netty5.0高级案例之请求响应同步通信
    [Err] 1091
    [Err] 23000
    [Err] 42000
    perl 爬取 find_by_tag_name
    perl 爬取html findvalues 方法
    perl 安装DBI和DBD
    js setTimeout 参数传递使用介绍
  • 原文地址:https://www.cnblogs.com/runninglzw/p/4591342.html
Copyright © 2011-2022 走看看