根据数组构建二叉树

// """
// 给定一个非空列表,一层一层的构建一个二叉树。

// 例如:
// input=[5,7,9,2,4,6,3,1,8,10]
   
// 我希望返回结果:
//          5(0)
//         /    \
//       7(1)     9(2)
//     /    \   /  \
//    2(3)      4(4)  6(5)   3(6)
//  /    \     /
// 1(7)   8(8) 10(9)  

// 请输出这个树每个节点和其子节点的值,以便我们确定这个树的构建是正确的。


// class TreeNode(object):
//     def __init__(self, x):
//         self.val = x
//         self.left = None
//         self.right = None


// #生成一个根结点,作为树的起始节点
// root=TreeNode(-1)

// """

#include <iostream>
#include <vector>
#include <queue>
#include <memory>
using namespace std;


class TreeNode{
    public: 
    TreeNode(int val):val_(val)
    {};
    TreeNode* left = nullptr;
    TreeNode* right = nullptr;
    int val_ = 0;
};

TreeNode* build(const vector<int>& nums,int index)
{    
    int n = nums.size();
    int left = 2 * index + 1;
    int right = 2 * index + 2;
    TreeNode* node = new TreeNode(nums[index]);    
    if(left > n - 1)node->left = nullptr;
    else
    node->left = build(nums,left);
    if(right > n - 1)node->right = nullptr;
    else node->right = build(nums,right);
    return node;

}

vector<vector<int>>levelOrder(TreeNode* root)
{    
    vector<vector<int>>res;
    if(nullptr == root)return res;
    queue<TreeNode*>q;
    q.push(root);
    while(!q.empty())
    {
        int size = q.size();
        vector<int>tmp;
        for(int i = 0; i < size; ++i)
        {
            TreeNode* cur = q.front();
            q.pop();
            tmp.push_back(cur->val_);
            if(cur->left)q.push(cur->left);
            if(cur->right)q.push(cur->right);
        }
        res.push_back(tmp);
    }
    return res;

    
}


int main()
{
    vector<int>nums{5,7,9,2,4,6,3,1,8,10};
    TreeNode* node = build(nums,0);
    auto res = levelOrder(node);
    for(auto nums:res)
    {
        for(auto num : nums)
        {
            cout << num <<" ";
        }
        cout << endl;
    }
    return 0;
}

 

posted @ 2022-08-15 08:47  fourmii  阅读(220)  评论(1编辑  收藏  举报