數據結構---二叉樹---平衡二叉樹(4 插入)

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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章