class Node<T>
{
private T data;
private Node<T> IChild;
private Node<T> rChild;
public T Data
{
get { return data; }
set { data = value; }
}
public Node<T> Rchild
{
get { return rChild; }
set { rChild = value; }
}
internal Node<T> LChild { get => IChild; set => IChild = value; }
public Node (T val,Node <T>Ip,Node<T>rp )
{
data = val;
IChild = Ip;
rChild = rp;
}
public Node( Node<T> Ip, Node<T> rp)
{
data = default(T);
IChild = Ip;
rChild = rp;
}
public Node(T val)
{
data = val;
IChild = null;
rChild = null;
}
public Node()
{
data = default(T);
IChild = null;
rChild = null;
}
}
//链表—二叉树
class BiTree<T>
{
private Node<T> head;
public Node<T> Head
{
get { return head; }
set { head = value; }
}
public BiTree()
{
head = null;
}
public BiTree(T val,Node<T>lp,Node<T>rp)
{
Node<T> p = new Node<T>(val,lp,rp );
head = p;
}
public BiTree(T val)
{
Node<T> p = new Node<T>(val);
head = p;
}
public bool IsEmpty()//是否为空树
{
return head == null ? true:false ;
}
public Node<T> Root()//获取根节点
{
return head;
}
public Node<T> GetLChild(Node<T>p)//获取左子孩子节点
{
return p.LChild;
}
public Node<T> GetRChild(Node<T> p)//获取右子孩子节点
{
return p.Rchild ;
}
//将结点p的左子树插入值为val的新结点,
//原来的左子树成为新结点的左子树
public void InsertL(T val,Node<T>p)
{
Node<T> temp = new Node<T>(val);
temp.LChild = p.LChild;
p.LChild = temp;
}
//将结点p的右子树插入值为val的新结点,
//原来的右子树成为新结点的右子树
public void InsertR(T val, Node<T> p)
{
Node<T> temp = new Node<T>(val);
temp.Rchild = p.Rchild ;
p.Rchild = temp;
}
//若p非空,删除p的左子树
public Node<T >DeleteL(Node<T>p)
{
if (p==null ||p.LChild==null )
{
return null;
}
if (p.LChild.Rchild==null )
{
Node<T> temp = p.LChild;
p.LChild = p.LChild.LChild;
//p.LChild = null;
return temp;
}
else
{
Node<T> temp = p.LChild;
Node<T> q = temp.Rchild;
while (q.LChild!=null )
{
q = q.LChild;
}
p.LChild = q;
q.Rchild = p.LChild.Rchild;
q.LChild = p.LChild.LChild;
return temp;
}
}
//判断是否是叶子结点
public bool IsLeaf(Node<T> p)
{
if (p!=null&&p.LChild==null&&p.Rchild==null )
{
return true;
}
else
{
return false;
}
}
public void InOeder(Node<T> root)
{
//节点为空
if (root==null )
{
return;
}
Console.WriteLine("{0}", root.Data);
//中序遍历左子树
InOeder(root.LChild);
//处理根节点
//中序遍历右子树
InOeder(root.Rchild);
}
public Node<T>DeleteR(Node <T> p)
{
if (p==null||p.Rchild==null )
{
return null ;
}
Node<T> temp = p.Rchild;
p.Rchild = null;
return temp;
}
public void Insert(T i)
{
Node<T> newNode = new Node<T>();
newNode.Data = i;
if (head == null)
head = newNode;
else
{
Node<T> current = head ;
Node<T> parent;
while (true)
{
parent = current;
if (Convert.ToInt32(i)< Convert.ToInt32(current.Data) )
{
current = current.LChild ;
if (current == null)
{
parent.LChild = newNode;
break;
}
}
else
{
current = current.Rchild ;
if (current == null)
{
parent.Rchild = newNode;
break;
}
}
}
}
}
}