../ Competitive Programming
-rw-r--r--aguang1.4 KiB1 min read

Leet Code Daily 2024-07-15 - Create Binary Tree From Descriptions

Code

c++
/**
 * Definition for a binary tree node.
 * 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) {}
 * };
 */
constexpr int kMaxSize = 100000;

class Solution {
public:
    TreeNode* createBinaryTree(vector<vector<int>>& descriptions) {

        vector<TreeNode*> nodes(kMaxSize, nullptr);
        auto getNode = [&](const int val) {
            if (nodes[val - 1] == nullptr) {
                nodes[val - 1] = new TreeNode(val);
            }
            return nodes[val - 1];
        };

        vector<bool> isRoot(kMaxSize, true);
        for (const auto desc : descriptions) {
            auto parent = getNode(desc[0]);
            if (desc[2] == 1) {
                parent->left = getNode(desc[1]);
            } else {
                parent->right = getNode(desc[1]);
            }
            isRoot[desc[1] - 1] = false;
        }

        for (int i = 0; i < kMaxSize; i++) {
            if (isRoot[i] && nodes[i] != nullptr) {
                return nodes[i];
            }
        }

        return nullptr;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window