第12章二叉搜索树
概要
施工中
基本操作的代码实现
基本操作包括Inorder_Tree_Walk、Minimum、Successor、Insert、Delete等。(主要是用c#实现,部分会在日后补上)
#region "二叉树基本操作"
/// <summary>
/// 非递归版的中序遍历
/// </summary>
/// <param name="x">头结点</param>
public static void Inorder_Tree_Walk(Node<int> x)
{
Stack<Node<int>> s = new Stack<Node<int>>();
while (s.Count != 0 || x != null)
{
while (x != null)
{
s.Push(x);
x = x.Left;
}
if (s.Count != 0)
{
var y = s.Pop();
Console.Write(y.key + "");
if (y.Right != null)
{
x = y.Right;
}
}
}
}
/// <summary>
/// 二叉树插入
/// </summary>
/// <param name="t">目标二叉树</param>
/// <param name="x">待插入结点</param>
public static void Tree_Insert(Tree<int> t, Node<int> x)
{
Node<int> y = null;
var z = t.Root;
while (z != null)
{
y = z;
z = z.key > x.key ? z.Left : z.Right;
}
x.Parent = y;
if (y == null)
{
t.Root = x;
}
else if (y.key > x.key)
{
y.Left = x;
}
else
{
y.Right = x;
}
}
/// <summary>
/// 二叉树删除
/// </summary>
/// <param name="t">目标二叉树</param>
/// <param name="z">待删除结点</param>
public static void Tree_Delete(Tree<int> t, Node<int> z)
{
if (z.Left == null)
{
Translate(t, z, z.Right);
}
else if (z.Right == null)
{
Translate(t, z, z.Left);
}
else
{
var y = Tree_Minimum(z.Right);
if (y.Parent != z)
{
Translate(t, y, y.Right);
z.Right.Parent = y;
y.Right = z.Right;
}
Translate(t, z, y);
z.Left.Parent = y;
y.Left = z.Left;
}
}
/// <summary>
/// 返回以x为头结点的子树的最小结点
/// </summary>
/// <param name="x">头结点</param>
/// <returns>最小结点</returns>
public static Node<int> Tree_Minimum(Node<int> x)
{
Node<int> y = null;
while (x != null)
{
y = x;
x = x.Left;
}
return y;
}
/// <summary>
/// 结点取代
/// </summary>
/// <param name="t">目标树</param>
/// <param name="n1">待取代点</param>
/// <param name="n2">取代结点</param>
private static void Translate(Tree<int> t, Node<int> n1, Node<int> n2)
{
if (n1.Parent == null)
{
t.Root = n2;
}
else if (n1.Parent.key > n1.key)
{
n1.Parent.Left = n2;
}
else
{
n1.Parent.Right = n2;
}
if (n2 != null)
{
n2.Parent = n1.Parent;
}
}
#endregion
12.4随机构建二叉树
施工中
第12章思考题
施工中