/** * File: tree_node.hpp * Created Time: 2021-12-19 * Author: krahets (krahets@163.com) */ #pragma once #include #include using namespace std; /* Binary tree node structure */ struct TreeNode { int val{}; int height = 0; TreeNode *parent{}; TreeNode *left{}; TreeNode *right{}; TreeNode() = default; explicit TreeNode(int x, TreeNode *parent = nullptr) : val(x), parent(parent) { } }; // For serialization encoding rules, refer to: // https://www.hello-algo.com/chapter_tree/array_representation_of_tree/ // Array representation of the binary tree: // [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15] // Linked list representation of the binary tree: // /——— 15 // /——— 7 // /——— 3 // | \——— 6 // | \——— 12 // ——— 1 // \——— 2 // | /——— 9 // \——— 4 // \——— 8 /* Deserialize a list into a binary tree: Recursively */ TreeNode *vectorToTreeDFS(vector &arr, int i) { if (i < 0 || i >= arr.size() || arr[i] == INT_MAX) { return nullptr; } TreeNode *root = new TreeNode(arr[i]); root->left = vectorToTreeDFS(arr, 2 * i + 1); root->right = vectorToTreeDFS(arr, 2 * i + 2); return root; } /* Deserialize a list into a binary tree */ TreeNode *vectorToTree(vector arr) { return vectorToTreeDFS(arr, 0); } /* Serialize a binary tree into a list: Recursively */ void treeToVecorDFS(TreeNode *root, int i, vector &res) { if (root == nullptr) return; while (i >= res.size()) { res.push_back(INT_MAX); } res[i] = root->val; treeToVecorDFS(root->left, 2 * i + 1, res); treeToVecorDFS(root->right, 2 * i + 2, res); } /* Serialize a binary tree into a list */ vector treeToVecor(TreeNode *root) { vector res; treeToVecorDFS(root, 0, res); return res; } /* Free memory allocated to the binary tree */ void freeMemoryTree(TreeNode *root) { if (root == nullptr) return; freeMemoryTree(root->left); freeMemoryTree(root->right); delete root; }