zoukankan      html  css  js  c++  java
  • 构建完全二叉树、控制台打印二叉树

    两段比较实用的代码,一个用于根据输入的数组构建一棵完全二叉树,一个用于在控制台打印二叉树,方便查看树的结构(打印二叉树的代码是在网上找的,现在找不到出处了,向作者抱歉)。

    //首先是节点的结构
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
        }
    };
    
    ///构建完全二叉树,用到了队列
    TreeNode * constructTree(int arr[], int length)
    {
        if (length <= 0) return NULL;
        list<TreeNode*> nodeList;
        TreeNode *root = new TreeNode(arr[0]);
        nodeList.push_back(root);
        for (int i = 1; i < length; i++)
        {
            TreeNode *node = new TreeNode(arr[i]);
            while (!nodeList.empty())
            {
                TreeNode *top = nodeList.front();
                if (!top->left)
                {
                    top->left = node;
                    nodeList.push_back(node);
                    break;
                }
                else if (!top->right)
                {
                    top->right = node;
                    nodeList.push_back(node);
                    break;
                }
                else
                    nodeList.pop_front();
            }
        }
        return root;
    }
    //打印二叉树,使用了先序遍历的方法
    void printTree(TreeNode *root, int blk = 0)
    {
        if (root == NULL)
            return;
        for (int i = 0; i < blk; i++) printf("    ");//缩进
        printf("|—<%d>
    ", root->val);//打印"|—<id>"形式
    
        printTree(root->left, blk + 1);//打印子树,累加缩进次数
        printTree(root->right, blk + 1);//打印子树,累加缩进次数    
    }
  • 相关阅读:
    flask为blueprint增加error_handler
    solr的moreLikeThis实现“相似数据”功能
    pgsql删除重复记录
    sqlalchemy的不区分大小写比较
    logrotate运行时间指定
    远程桌面剪贴板失效的解决方法
    github上关于campbell数据采集的一些代码。
    python 学习笔记
    guestfs-python 手册
    [KVM][guestfs] 安装 guestfs-python 出错
  • 原文地址:https://www.cnblogs.com/cLockey/p/4769372.html
Copyright © 2011-2022 走看看