1、创建BSNode类。
namespace Algorithm
{
public class BSNode
{
public int data;
public BSNode leftChild=null;
public BSNode rightChild=null;
public BSNode parent=null;
public BSNode(int data)
{
this.data = data;
}
}
}
2、创建BSTree类,实现添加,查找与删除功能。
using System.Collections.Generic;
namespace Algorithm
{
public class BSTree
{
public BSNode root = null;
public void Add(int item)
{
BSNode newNode = new BSNode(item);
if (root == null)
{
root = newNode;
}
else
{
BSNode tempNode = root;
while (true)
{
if (item < tempNode.data)
{
if (tempNode.leftChild == null)
{
tempNode.leftChild = newNode;
newNode.parent = tempNode;
break;
}
tempNode = tempNode.leftChild;
}
else
{
if (tempNode.rightChild == null)
{
tempNode.rightChild = newNode;
newNode.parent = tempNode;
break;
}
tempNode = tempNode.rightChild;
}
}
}
}
public List<int> Sort()
{
tempList = new List<int>();
SortNode(root);
return tempList;
}
private List<int> tempList;
private void SortNode(BSNode node)
{
if (node == null) return;
SortNode(node.leftChild);
tempList.Add(node.data);
SortNode(node.rightChild);
}
public BSNode FindNode(int item)
{
BSNode tempNode = root;
while (tempNode != null)
{
if (item < tempNode.data)
{
tempNode = tempNode.leftChild;
}
else if (item > tempNode.data)
{
tempNode = tempNode.rightChild;
}
else
{
return tempNode;
}
}
return null;
}
public bool DeleteNode(int item)
{
BSNode deleteNode = FindNode(item);
return DeleteNode(deleteNode);
}
private bool DeleteNode(BSNode deleteNode)
{
if (deleteNode == null) return false;
if (deleteNode.leftChild == null && deleteNode.rightChild == null)
{
if (deleteNode.parent == null)
{
root = null;
}
else if (deleteNode.parent.leftChild == deleteNode)
{
deleteNode.parent.leftChild = null;
deleteNode.parent = null;
}
else
{
deleteNode.parent.rightChild = null;
deleteNode.parent = null;
}
}
else if (deleteNode.leftChild == null && deleteNode.rightChild != null)
{
if (deleteNode.parent.leftChild == deleteNode)
{
deleteNode.parent.leftChild = deleteNode.rightChild;
deleteNode.rightChild.parent = deleteNode.parent;
}
else
{
deleteNode.parent.rightChild = deleteNode.rightChild;
deleteNode.rightChild.parent = deleteNode.parent;
}
}
else if (deleteNode.leftChild != null && deleteNode.rightChild == null)
{
if (deleteNode.parent.leftChild == deleteNode)
{
deleteNode.parent.leftChild = deleteNode.leftChild;
deleteNode.leftChild.parent = deleteNode.parent;
}
else
{
deleteNode.parent.rightChild = deleteNode.leftChild;
deleteNode.leftChild.parent = deleteNode.parent;
}
}
else
{
BSNode tempNode = GetMinNode(deleteNode.rightChild);
deleteNode.data = tempNode.data;
DeleteNode(tempNode);
}
return true;
}
private BSNode GetMinNode(BSNode node)
{
while (node.leftChild != null)
{
node = node.leftChild;
}
return node;
}
}
}