zoukankan      html  css  js  c++  java
  • 数据结构-从上往下打印二叉树

    题目:从上往下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

    分析:其实就是按层的遍历方式

    /*
    剑指offer面试题23
    */
    #include <iostream>
    #include <deque>
    
    using namespace std;
    
    struct BinaryTree{
        int data;
        BinaryTree* lchild;
        BinaryTree* rchild;
    };
    
    void PrintLeverTree(BinaryTree* root){
        if(root == NULL){
            return;
        }
    
        deque<BinaryTree* > prioriDeque;
        prioriDeque.push_back(root);
    
        while(prioriDeque.size()){
            BinaryTree* pNode = prioriDeque.front();
            prioriDeque.pop_front();
    
            cout << pNode->data << " ";
    
            if(pNode->lchild){
                prioriDeque.push_back(pNode->lchild);
            }
            if(pNode->rchild){
                prioriDeque.push_back(pNode->rchild);
            }
        }
    }
    
    BinaryTree* Create(){
        BinaryTree* root = new BinaryTree;
        root->data = 8;
        BinaryTree* lchild = new BinaryTree;
        lchild->data = 6;
        BinaryTree* rchild = new BinaryTree;
        rchild->data = 10;
        root->lchild = lchild;
        root->rchild = rchild;
    
        BinaryTree* lchild1 = new BinaryTree;
        lchild1->data = 5;
        BinaryTree* rchild1 = new BinaryTree;
        rchild1->data = 7;
        lchild->lchild = lchild1;
        lchild->rchild = rchild1;
    
        BinaryTree* lchild2 = new BinaryTree;
        lchild2->data = 9;
        BinaryTree* rchild2 = new BinaryTree;
        rchild2->data = 11;
        rchild->lchild = lchild2;
        rchild->rchild = rchild2;
        return root;
    }
    
    int main()
    {
        BinaryTree* root = Create();
    
        PrintLeverTree(root);
    
        return 0;
    }
  • 相关阅读:
    css 学习笔记 菜鸟
    html学习 菜鸟
    flask 杂记2
    logging 为全局的日志工具对象添加日志记录器
    flask 框架 转载:https://cloud.tencent.com/developer/article/1465968
    flask 框架 转载:https://cloud.tencent.com/developer/article/1465949
    flask blueprint
    [ZJOI2005]午餐
    [ZJOI2006]皇帝的烦恼
    数位dp小练
  • 原文地址:https://www.cnblogs.com/wn19910213/p/3737708.html
Copyright © 2011-2022 走看看