You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
1.7 KiB
73 lines
1.7 KiB
2 years ago
|
/**
|
||
2 years ago
|
* File: tree_node.hpp
|
||
2 years ago
|
* Created Time: 2021-12-19
|
||
|
* Author: Krahets (krahets@163.com)
|
||
|
*/
|
||
|
|
||
|
#pragma once
|
||
|
|
||
2 years ago
|
#include <limits.h>
|
||
|
|
||
2 years ago
|
/* Definition for a binary tree node */
|
||
2 years ago
|
struct TreeNode {
|
||
2 years ago
|
int val{};
|
||
2 years ago
|
int height = 0;
|
||
2 years ago
|
TreeNode *parent{};
|
||
|
TreeNode *left{};
|
||
|
TreeNode *right{};
|
||
|
TreeNode() = default;
|
||
2 years ago
|
explicit TreeNode(int x, TreeNode *parent = nullptr) : val(x), parent(parent) {
|
||
|
}
|
||
2 years ago
|
};
|
||
|
|
||
2 years ago
|
/* Generate a binary tree with a vector */
|
||
2 years ago
|
TreeNode *vecToTree(vector<int> list) {
|
||
2 years ago
|
if (list.empty())
|
||
2 years ago
|
return nullptr;
|
||
|
|
||
|
auto *root = new TreeNode(list[0]);
|
||
|
queue<TreeNode *> que;
|
||
2 years ago
|
que.emplace(root);
|
||
2 years ago
|
size_t n = list.size(), i = 0;
|
||
2 years ago
|
while (!que.empty()) {
|
||
2 years ago
|
auto node = que.front();
|
||
2 years ago
|
que.pop();
|
||
2 years ago
|
if (++i >= n)
|
||
2 years ago
|
break;
|
||
2 years ago
|
// INT_MAX represent null
|
||
|
if (list[i] != INT_MAX) {
|
||
|
node->left = new TreeNode(list[i]);
|
||
2 years ago
|
que.emplace(node->left);
|
||
|
}
|
||
2 years ago
|
if (++i >= n)
|
||
2 years ago
|
break;
|
||
2 years ago
|
if (list[i] != INT_MAX) {
|
||
|
node->right = new TreeNode(list[i]);
|
||
2 years ago
|
que.emplace(node->right);
|
||
|
}
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
return root;
|
||
|
}
|
||
|
|
||
2 years ago
|
/* Get a tree node with specific value in a binary tree */
|
||
2 years ago
|
TreeNode *getTreeNode(TreeNode *root, int val) {
|
||
2 years ago
|
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;
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
/* Free the memory allocated to a tree */
|
||
2 years ago
|
void freeMemoryTree(TreeNode *root) {
|
||
2 years ago
|
if (root == nullptr)
|
||
|
return;
|
||
|
freeMemoryTree(root->left);
|
||
2 years ago
|
freeMemoryTree(root->right);
|
||
|
// 释放内存
|
||
2 years ago
|
delete root;
|
||
2 years ago
|
}
|