1. 程式人生 > 其它 >樹的基礎知識(三)

樹的基礎知識(三)

樹的基礎知識(三)

二叉搜尋樹

  • 左小右大
  • 左右子樹均為二叉搜尋樹

特別函式

Position Find( ElementType X, BinTree BST ):從二叉搜尋樹BST中查詢元素X,返回其所在結點的地址:

Position Find( ElementType x, BinTree BST ){
	if( !BST ) return NULL; /*查詢失敗*/

	if( X >BST->Data ) return Find( x, BST->Right ); /*在右子樹中繼續查詢*/
Else if( X < BST->Data ) return Find( x, BST->Left ); /*在左子樹中繼續查詢*/ else /*X == BST->Data */ return BST; /*查詢成功,返回結點的找到結點的地址*/ }

Position FindMin( BinTree BST ):從二叉搜尋樹BST中查詢並返回最小元素所在結點的地址:

//查詢最小元素(尾遞迴)
Position FindMin(BiTree T)
{
	if (!T)
		return NULL;
	else if (!T->lchild)
		return
T; else return FindMin(T->lchild); }

Position FindMax( BinTree BST):從二叉搜尋樹BST中查詢並返回最大元素所在結點的地址。

//查詢最大元素(迭代)
Position FindMax(BiTree T)
{
	if (T)/*沒有該判斷語句 對空樹是不安全的*/
	{
		while (T->rchild)
			T = T->rchild;
	}
	return T;
}

BinTree Insert( ElementType X, BinTree BST )o BinTree Delete( ElementType X, BinTree BST )

//插入元素(遞迴)
//最終返回元素為根節點指標
BiTree Insert(int data, BiTree T)
{
	if (!T)//找到插入位置,進行插入
	{
		T = (BiTree)malloc(sizeof(BiTNode));
		T->data = data;
		T->lchild = T->rchild = NULL;
	}
	else if (data > T->data)//進行右子樹遞迴插入
		T->rchild = Insert(data, T->rchild);
	else if (data < T->data)//進行左子樹遞迴插入
		T->lchild = Insert(data, T->lchild);
        else//插入失敗
                printf("元素已經存在,插入失敗");
	return T;
}

平衡二叉樹

樹的查詢效率–平均查詢長度(ASL)

求平均查詢長度

查詢成功的情況下:
第一層結點:一個 查找了一次
第二層結點:二個 每個查詢兩次
第三層結點:三個 每個查詢三次
第四層結點:三個 每個查詢四次
第五層結點:二個 每個查詢五次
第六層結點:一個 每個查詢六次
在這裡插入圖片描述
在這裡插入圖片描述

衡量是平衡二叉樹條件

  • 空樹
  • 左右兩邊高度差絕對值不超過1,|hl-hr|<=1

高度為h的平衡二叉樹的最少結點樹:在這裡插入圖片描述
n個結點平衡二叉樹的查詢效率是O(log2n)

平衡二叉樹調整

搜尋樹–左邊小,右邊大

  • RR旋轉
  • LL旋轉
  • RL旋轉
  • LR旋轉