hello-algo/codes/cpp/utils/tree_node.hpp

73 lines
1.7 KiB
C++
Raw Normal View History

/**
* File: tree_node.hpp
* Created Time: 2021-12-19
* Author: Krahets (krahets@163.com)
*/
#pragma once
2023-04-18 14:31:23 +08:00
#include <limits.h>
/* Definition for a binary tree node */
struct TreeNode {
int val{};
2022-12-04 08:22:37 +08:00
int height = 0;
TreeNode *parent{};
TreeNode *left{};
TreeNode *right{};
TreeNode() = default;
explicit TreeNode(int x, TreeNode *parent = nullptr) : val(x), parent(parent) {
}
};
/* Generate a binary tree with a vector */
TreeNode *vecToTree(vector<int> list) {
if (list.empty())
return nullptr;
auto *root = new TreeNode(list[0]);
queue<TreeNode *> que;
que.emplace(root);
2023-04-18 14:31:23 +08:00
size_t n = list.size(), i = 0;
while (!que.empty()) {
auto node = que.front();
que.pop();
2023-04-18 14:31:23 +08:00
if (++i >= n)
break;
2023-04-18 14:31:23 +08:00
// INT_MAX represent null
if (list[i] != INT_MAX) {
node->left = new TreeNode(list[i]);
que.emplace(node->left);
}
2023-04-18 14:31:23 +08:00
if (++i >= n)
break;
2023-04-18 14:31:23 +08:00
if (list[i] != INT_MAX) {
node->right = new TreeNode(list[i]);
que.emplace(node->right);
}
}
return root;
}
/* Get a tree node with specific value in a binary tree */
TreeNode *getTreeNode(TreeNode *root, int val) {
if (root == nullptr)
return nullptr;
if (root->val == val)
return root;
TreeNode *left = getTreeNode(root->left, val);
TreeNode *right = getTreeNode(root->right, val);
return left != nullptr ? left : right;
}
2023-01-14 19:52:11 +08:00
/* Free the memory allocated to a tree */
2023-01-14 19:52:11 +08:00
void freeMemoryTree(TreeNode *root) {
if (root == nullptr)
return;
freeMemoryTree(root->left);
2023-01-14 19:52:11 +08:00
freeMemoryTree(root->right);
// 释放内存
delete root;
2023-01-14 19:52:11 +08:00
}