二叉查找树的 C# 实现
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace BinarySearchTree
- {
- public class Node
- {
- public int Data;
- public Node Left;
- public Node Right;
- public void DisplayNode()
- {
- Console.WriteLine(Data);
- }
- }
- public class BinarySearchTree
- {
- public Node root;
- public BinarySearchTree()
- {
- root = null;
- }
- public void Insert(int i)
- {
- Node newNode = new Node();
- newNode.Data = i;
- if (root == null)
- root = newNode;
- else
- {
- Node current = root;
- Node parent;
- while (true)
- {
- parent = current;
- if (i < current.Data)
- {
- current = current.Left;
- if (current == null)
- {
- parent.Left = newNode;
- break;
- }
- }
- else
- {
- current = current.Right;
- if (current == null)
- {
- parent.Right = newNode;
- break;
- }
- }
- }
- }
- }
- public void InOrder(Node theRoot)
- {
- if (!(theRoot == null))
- {
- InOrder(theRoot.Left);
- theRoot.DisplayNode();
- InOrder(theRoot.Right);
- }
- }
- public int FindMax()
- {
- Node current = root;
- while (!(current.Right == null))
- current = current.Right;
- return current.Data;
- }
- public Node Find(int key)
- {
- Node current = root;
- while (current.Data != key)
- {
- if (key < current.Data)
- current = current.Left;
- else
- current = current.Right;
- if (current == null)
- return null;
- }
- return current;
- }
- public bool Delete(int key)
- {
- Node current = root;
- Node parent = root;
- bool isLeftChild = true;
- while (current.Data != key)
- {
- parent = current;
- if (key < current.Data)
- {
- isLeftChild = true;
- current = current.Left;
- }
- else
- {
- isLeftChild = false;
- current = current.Right;
- }
- if (current == null)
- return false;
- }
- if ((current.Left == null) && (current.Right == null))
- {
- if (current == root)
- root = null;
- else if (isLeftChild)
- parent.Left = null;
- else
- parent.Right = null;
- }
- else if (current.Right == null)
- if (current == root)
- root = current.Left;
- else if (isLeftChild)
- parent.Left = current.Left;
- else
- parent.Right = current.Left;
- else if (current.Left == null)
- if (current == root)
- root = current.Right;
- else if (isLeftChild)
- parent.Left = current.Right;
- else
- parent.Right = current.Right;
- else
- {
- Node successor = GetSuccessor(current);
- if (current == root)
- root = successor;
- else if (isLeftChild)
- parent.Left = successor;
- else
- parent.Right = successor;
- successor.Left = current.Left;
- }
- return true;
- }
- public Node GetSuccessor(Node delNode)
- {
- Node successorParent = delNode;
- Node successor = delNode;
- Node current = delNode.Right;
- while (current != null)
- {
- successorParent = successor;
- successor = current;
- current = current.Left;
- }
- if (successor != delNode.Right)
- {
- successorParent.Left = successor.Right;
- successor.Right = delNode.Right;
- }
- return successor;
- }
- }
- }