Esempio n. 1
0
 public node(int n)
 {
     data  = n;
     left  = null;
     right = null;
 }
Esempio n. 2
0
        private node delete(int n)
        {
            node temp;
            node ptr1 = root;
            node ptr2 = ptr1.Left;

            while (ptr2 != null)
            {
                if (ptr2.Data == n)
                {
                    break;
                }
                ptr1 = ptr2;
                if (n < ptr2.Data)
                {
                    ptr2 = ptr2.Left;
                }
                else
                {
                    ptr2 = ptr2.Right;
                }
            }
            if (ptr2 == null)
            {
                MessageBox.Show("資料" + n.ToString() + "不存在");
                return(null);
            }
            else
            {
                if (ptr2.Left != null && ptr2.Right != null)
                {
                    int ttq = 0;
                    temp = ptr2.Left;
                    while (temp.Right != null)
                    {
                        temp = temp.Right;
                    }
                    ttq = temp.Data;
                    delete(temp.Data);
                    ptr2.Data = ttq;
                }
                else if (ptr2.Left != null || ptr2.Right != null)
                {
                    if (ptr1.Left != null && ptr2.Data == ptr1.Left.Data)
                    {
                        if (ptr2.Left != null)
                        {
                            ptr1.Left = ptr2.Left;
                        }
                        else
                        {
                            ptr1.Left = ptr2.Right;
                        }
                    }
                    else
                    {
                        if (ptr2.Left != null)
                        {
                            ptr1.Right = ptr2.Left;
                        }
                        else
                        {
                            ptr1.Right = ptr2.Right;
                        }
                    }
                }
                else
                {
                    if (ptr1.Left != null && ptr2.Data == ptr1.Left.Data)
                    {
                        ptr1.Left = null;
                    }
                    else
                    {
                        ptr1.Right = null;
                    }
                }
            }
            return(null);
        }