0.简介
前面主要的二叉树理论部分介绍,这里开始实践。
1.插入
输入一个元素,树在插入的过程中就会调整。
#include<iostream>
#include <algorithm>
using namespace std;
struct TreeNode
{
TreeNode(){}
TreeNode(int n,int h):num(n),height(h) {}
int num = 0;
int height = 0;
TreeNode* left = nullptr;
TreeNode* right = nullptr;
TreeNode* parent = nullptr;
};
inline int getHeight(TreeNode* root)
{
return root ? root->height : 0;
}
void condition1(TreeNode*& root)
{
/* A
/
B
/
C
*/
TreeNode* A = root;
TreeNode* B = root->left;
A->left = B->right;
B->parent = A->parent;
A->parent = B;
B->right = A;
root = B;
}
void condition2(TreeNode*& root)
{
/*A
\
B
\
C
*/
TreeNode* A = root;
TreeNode* B = root->right;
A->right = B->left;
B->parent = A->parent;
A->parent = B;
B->left = A;
root = B;
}
void condition3(TreeNode*& root)
{
/* A
/
B
\
C
*/
TreeNode* A = root;
TreeNode* B = root->left;
TreeNode* C = root->left->right;
A->left = C->right;
B->right = C->left;
C->left = B;
C->right = A;
C->parent = A->parent;
B->parent = C;
A->parent = A;
root = C;
}
void condition4(TreeNode*& root)
{
/* A
\
B
/
C
*/
TreeNode* A = root;
TreeNode* B = root->right;
TreeNode* C = root->right->left;
A->right = C->left;
B->left = C->right;
C->right = B;
C->left = A;
C->parent = A->parent;
B->parent = C;
A->parent = A;
root = C;
}
int addNode(TreeNode* &root,int num)
{
//如果节点的空
if (root == nullptr)
{
//创建节点
root = new TreeNode(num,1);
//返回树高
return 1;
}
int lHeight = getHeight(root->left), rHeight = getHeight(root->right);
//左子树
if (num < root->num)
{
//添加节点
lHeight = addNode(root->left, num);
//修改父节点
root->left->parent = root;
}
//右子树
else
{
//添加节点
rHeight = addNode(root->right, num);
//修改父节点
root->right->parent = root;
}
//调整树
if (abs(lHeight - rHeight) > 1)
{
if (lHeight> rHeight)
{
if (getHeight(root->left->left) > getHeight(root->left->right))
condition1(root);
else
condition3(root);
}
else
{
if (getHeight(root->right->right) > getHeight(root->right->left))
condition2(root);
else
condition4(root);
}
}
return root->height = max(lHeight , rHeight) + 1;
}
int main()
{
TreeNode* root = nullptr;
addNode(root,12);
addNode(root, 5);
addNode(root, 15);
addNode(root,3);
addNode(root, 8);
addNode(root, 9);
return 0;
}