• 周二. 4月 23rd, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

二叉树建树

admin

11月 28, 2021

根据一个数组来建一棵二叉树

#include<iostream>
#include<vector>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    // TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

TreeNode* newNode(int val) {
    if (val == -1) {
        return nullptr;
    }

    TreeNode* node = new TreeNode;
    node->left = nullptr;
    node->right = nullptr;
    node->val = val;
    return node;    
}

TreeNode* preOrder(TreeNode* node, const vector<int> &arr ,const int index) {
    if (index > arr.size() || arr[index] == -1) {
        return nullptr;
    }
    if (node == nullptr ) {
        node = newNode(arr[index]); 
    }
    node->left = preOrder(node->left, arr, index*2+1);
    node->right = preOrder(node->right, arr, index*2+2);
    return node;
}

TreeNode* createTree(const vector<int>& treeArr) {
    TreeNode* root = nullptr;
    preOrder(root, treeArr, 0);
}

int main() {
    vector<int> arr = {3, 9, 20, -1, -1, 15, 7};
    TreeNode* root = createTree(arr);
    return 0;
}

《二叉树建树》有一个想法
  1. Erec Prime is a natural formula designed to boost your virility and improve your male enhancement abilities, helping you maintain long-lasting performance. This product is ideal for men facing challenges with maintaining strong erections and desiring to enhance both their size and overall health. https://erecprimebuynow.us/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注