mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-06 14:27:26 +08:00
Add the initial EN translation for C++ code (#1346)
This commit is contained in:
84
en/codes/cpp/utils/tree_node.hpp
Normal file
84
en/codes/cpp/utils/tree_node.hpp
Normal file
@ -0,0 +1,84 @@
|
||||
/**
|
||||
* File: tree_node.hpp
|
||||
* Created Time: 2021-12-19
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <limits.h>
|
||||
#include <vector>
|
||||
|
||||
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<int> &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<int> arr) {
|
||||
return vectorToTreeDFS(arr, 0);
|
||||
}
|
||||
|
||||
/* Serialize a binary tree into a list: Recursively */
|
||||
void treeToVecorDFS(TreeNode *root, int i, vector<int> &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<int> treeToVecor(TreeNode *root) {
|
||||
vector<int> 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;
|
||||
}
|
Reference in New Issue
Block a user