示例#1
0
        /// <summary>
        ///Recursive function to deleteNode
        ///This function takes pointer to the root node. Deletes the given node.
        ///and then passes the pointer to the root node.
        /// </summary>
        /// <param name="node"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private BinaryTreeNode DeleteNode(BinaryTreeNode node, int key)
        {
            //If node is null return null

            if (node == null)
            {
                return(node);
            }

            /* Otherwise recursively go down the tree*/
            if (key < node.GetData())
            {
                var child = DeleteNode(node.Left, key);
                node.Left = child;
                if (child != null)
                {
                    child.Parent = node;
                }
            }
            else if (key > node.GetData())
            {
                var child = DeleteNode(node.Right, key);
                node.Right = child;
                if (child != null)
                {
                    child.Parent = node;
                }
            }
            else // if node.GetData() == key, then this is the node to be deleted.
            {
                // if the node is leaf node.
                if (node.Left == null && node.Right == null)
                {
                    node.Parent = null;
                    return(null);
                }

                // If node having only one child.
                if (node.Left == null)
                {
                    node.Parent = null;
                    var rightChild = node.Right;
                    node.Right = null;
                    return(rightChild);
                }
                else if (node.Right == null)
                {
                    node.Parent = null;
                    var leftChild = node.Left;
                    node.Left = null;
                    return(leftChild);
                }

                //if both left and right childs are present then,
                //Either replace it with successor or with predecessor

                //Here replacing it with successor
                var successor = GetSuccessor(node.Right);
                node.SetData(successor.GetData());

                node.Right = DeleteNode(node.Right, successor.GetData());
                return(node);
            }
            //Returning the root node after processing.
            return(node);
        }
示例#2
0
 public BinaryTree(BinaryTreeNode root)
 {
     this.Root = root;
 }