0.簡介
本篇博客是爲面平衡二叉樹,B樹,紅黑樹鋪墊,所以這裏就簡單實現創建一個樹。
1.創建樹
代碼中有詳細註釋,就不再寫多餘的句子了。
這個樹的創建是根據左小右大的順序建成。
#include<iostream>
#include <algorithm>
using namespace std;
struct TreeNode
{
int num = 0;
int height = 0;
TreeNode* left = nullptr;
TreeNode* right = nullptr;
TreeNode* parent = nullptr;
};
TreeNode* addNode(TreeNode*root,int num)
{
//如果是空節點的時候,則創建新節點
if (root == nullptr)
{
root = new TreeNode;
root->num = num;
root->height = 1;
return root;
}
//計算樹高
int lefth = 0, righth = 0;
if (root->left != nullptr)
lefth = root->left->height;
if (root->right != nullptr)
righth = root->right->height;
if (num > root->num)
{
//添加一個結點
root->right = addNode(root->right, num);
//獲取當前分支樹高
righth = root->right->height;
//父節點賦值
root->right->parent = root;
}
else
{
//添加一個結點
root->left = addNode(root->left, num);
//父節點賦值
root->right->left = root;
//獲取當點分支樹高
lefth = root->left->height;
}
//樹高計算
root->height = max(lefth ,righth) + 1;
return root;
}
int main()
{
TreeNode* root = nullptr;
root = addNode(root, 10);
addNode(root, 12);
addNode(root, 14);
addNode(root, 20);
addNode(root, 21);
cout << root->height << endl;
return 0;
}