zoukankan      html  css  js  c++  java
  • 创建单链表、二叉树(C++)

    https://blog.csdn.net/qq_43827595/article/details/104672938

    链表创建:

    #include <iostream>
    
    using namespace std;
    
    struct ListNode {
        int data;
        ListNode *next;
        ListNode(int x): data(x), next(NULL) {}
    };
    
    int main() {
        // Create a single linked list 1->2->3->4->NULL 1->2->3->4->NULL
        ListNode *head = new ListNode(-1);
        ListNode *a = head;
        for (int i = 1; i <= 4; i ++) {
            ListNode *b = new ListNode(i);
            // 尾插法
            a->next = b;
            a = b;
        }
        a->next = NULL;
    
        // 遍历输出链表
        ListNode *p = head->next;
        while(p != NULL) {
            printf("%d ", p->data);
            p = p->next;
        }
        puts("");
    
        return 0;
    }
    

      

    二叉树创建:

    #include <iostream>
    using namespace std;
    
    // 定义二叉树结点
    struct TreeNode {
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode(int x)
            : val(x)
            , left(NULL)
            , right(NULL) {
        }
    };
    
    // 核心:构建一棵二叉树 input数据必须是二叉树前序遍历结果,用-1表示空结点
    /*
    tree:
           3
        5    -1
     -1  -1
    input:
    3 5 -1 -1 -1
    */
    TreeNode *buildTree() {
        int d;
        cin >> d;
        if (d == -1) return NULL;
    
        TreeNode *root = new TreeNode(d);
        root->left = buildTree();
        root->right = buildTree();
        return root;
    }
    
    // 二叉树的中序遍历
    void inorderTraversal(TreeNode *root) {
        if (root == NULL) return;
    
        inorderTraversal(root->left);
        cout << root->val << " ";
        inorderTraversal(root->right);
    }
    
    int main() {
        auto root = buildTree();
        inorderTraversal(root);
        return 0;
    }
    

      

    输入数据:3 4 -1 -1 5 -1 -1

    输出结果:4 3 5 

  • 相关阅读:
    小程序开发 access_token 统一管理
    python操作mysql
    Mac版本的idea非正常关闭后,idea打开项目大面积报红
    PySpider爬取去哪儿攻略数据项目
    Python3.9安装PySpider步骤及问题解决
    Selenium 自动化测试工具
    Python 抓取猫眼电影排行
    Python爬虫基本库
    Python 创建一个Django项目
    Python 数据可视化
  • 原文地址:https://www.cnblogs.com/Allen-rg/p/13984814.html
Copyright © 2011-2022 走看看