Console.WriteLine("删除根节点 50, n中序遍历后:"); //删除根节点 DeleteBST(ref bsTree, 50);
LDR_BST(bsTree);
}
///<summary> /// 定义一个二叉排序树结构 ///</summary> public class BSTree { public int data; public BSTree left; public BSTree right; }
///<summary> /// 二叉排序树的插入操作 ///</summary> ///<param>排序树</param> ///<param>插入数</param> ///<param>是否执行了if语句</param> static void InsertBST(BSTree bsTree, int key, ref bool isExcute) { if (bsTree == null) return;
//如果父节点大于key,则遍历左子树 if (bsTree.data > key) InsertBST(bsTree.left, key, ref isExcute); else InsertBST(bsTree.right, key, ref isExcute);
if (!isExcute) { //构建当前节点 BSTree current = new BSTree() { data = key, left = null, right = null };
//插入到父节点的当前元素 if (bsTree.data > key) bsTree.left = current; else bsTree.right = current;
isExcute = true; }
}
///<summary> /// 创建二叉排序树 ///</summary> ///<param></param> static BSTree CreateBST(List<int> list) { //构建BST中的根节点 BSTree bsTree = new BSTree() { data = list[0], left = null, right = null };
for (int i = 1; i < list.Count; i++) { bool isExcute = false; InsertBST(bsTree, list[i], ref isExcute); } return bsTree; }
///<summary> /// 在排序二叉树中搜索指定节点 ///</summary> ///<param></param> ///<param></param> ///<returns></returns> static bool SearchBST(BSTree bsTree, int key) { //如果bsTree为空,说明已经遍历到头了 if (bsTree == null) return false;
if (bsTree.data == key) return true;
(编辑:焦作站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|