手寫實現搜尋二叉樹:
class treenode
; treenode* left_son = null;
treenode* right_son = null;
treenode* p = null; //一定儲存雙親的指標
intvalue = 0;
};
bool treeinsert(treenode*& proot,int value)
else
if (pcur->value>value)
else
}if (pparent ==
null)//空樹
else
if ( pparent->valueelse
//插左邊
return
true;
}
treenode* treemax(treenode* proot)
return proot;
}treenode* treemin(treenode* proot)
return proot;
}
treenode* successor(treenode* proot)
if (proot->right_son !=
null)// 當前節點有右孩子
treenode* pchild = proot;
treenode* pparent = pchild->p;
while (pparent !=
null
&&pparent->right_son == pchild)//當前節點無右孩子,尋找滿足要求的最底層祖先
return pparent;
}treenode* processor(treenode* proot)
if (proot->left_son !=
null)//有左孩子
treenode* pchild = proot;
treenode* pparent = pchild->p;
while (pparent !=
null
&&pparent->left_son == pchild)//無左孩子,尋找滿足要求的最底層祖先
return pparent;
}
bool transplant(treenode *& proot, treenode* pold, treenode* pnew)
//調整父節點的指標
if (pold->p ==
null)//父節點為空:替換了根節點
else
else
}//調整指向父節點的指標
if (pnew !=
null)//新子樹不為空
return
true;
}
void treedelete(treenode*& proot, treenode* pdelete)
else
if (pdelete->right_son ==
null)
else
//同時有兩個孩子時
transplant(proot,pdelete, successor);//後繼接管被刪節點的雙親
successor->left_son = pdelete->left_son;//後繼接管被刪節點的左孩子
successor->left_son->p = successor;
}}
void treeprint(treenode* proot)
treeprint(proot->left_son);
cout << proot->value <<
" ";
treeprint(proot->right_son);
}int main()
資料結構 搜尋二叉樹
它要麼是一顆空樹,要麼是具有以下性質的一顆樹 1 每個節點都有乙個作為搜尋依據的關鍵碼 key 並且每個關鍵碼都不相同 2 左子樹上的所有節點的關鍵碼都小於根節點的關鍵碼 3 右子樹上的所有節點的關鍵碼都大於根節點的關鍵碼 4 左右子樹都是搜尋二叉樹 由於它亦是乙個二叉樹,所以一些拷貝構造,析構等的...
二叉搜尋樹c 資料結構二叉搜尋樹
在n個動態的整數中搜尋某個整數?檢視其是否存在 假設使用動態陣列存放元素,從第 0 個位置開始遍歷搜尋,平均時間複雜度 o n 如果維護乙個有序的動態陣列,使用二分搜尋,最壞時間複雜度 o logn 但是新增 刪除的平均時間複雜度是 o n 針對這個需求,有沒有更好的方案?今天我們主要講的就是二叉搜...
資料結構 二叉樹 反轉二叉樹
include using namespace std define maxsize 1000 struct binary tree node class queue queue queue void queue push binary tree node btn binary tree node ...