LeetCode 构建树(C++)

注意:当节点的值为0时,会发生误判(0 和 NULL 的值相等)

#include 
#include 
#include 
using namespace std;

typedef struct TreeNode *Tree;

// Leetcode 树的结构体
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr)
    {
    }
    TreeNode(int x) : val(x), left(nullptr), right(nullptr)
    {
    }
    TreeNode(int x, TreeNode *left, TreeNode *right) :
        val(x), left(left), right(right)
    {
    }
};

Tree buildTree(const vector &num, int root = 0)
{
    if (num.size() < 1) { return nullptr; }
    if (root > num.size() - 1) { return nullptr; }
    if (num[root] == NULL) { return nullptr; }

    Tree T;
    T = new struct TreeNode;
    T->val = num[root];
    T->left = buildTree(num, (root + 1) * 2 - 1);
    T->right = buildTree(num, (root + 1) * 2);
    return T;
}

void listTree(const Tree &T)
{
    if (!T) { return; }
    queue q;
    q.push(T);
    while (!q.empty())
    {
        Tree temp = q.front();
        q.pop();
        if (temp == nullptr) { continue; }
        cout << temp->val << "  ";
        if (temp->left) { q.push(temp->left); }
        if (temp->right) { q.push(temp->right); }
    }
}

void handleVector(vector &num)
{
    queue vectorTempQueue;
    int size = num.size();
    for (int i = 0; i < size; i++)
    {
        if (num[i] == NULL)
        {
            vectorTempQueue.push(i);
            continue;
        }
        if (!vectorTempQueue.empty()
            && i == (vectorTempQueue.front() + 1) * 2 - 1)
        {
            num.insert(num.begin() + i, 2, NULL);
            size = num.size();
            i = i + 1;
            vectorTempQueue.pop();
        }
    }
}

int main()
{
    Tree T;
    vector num = {1, NULL, 2, 3};
    handleVector(num);
    T = buildTree(num);
    listTree(T);
    return 0;
}

你可能感兴趣的:(leetcode,c++,算法)