Quantcast
Channel: Visual C# forum
Viewing all articles
Browse latest Browse all 31927

Delete a node in Binary Tree failed

$
0
0

I am going to delete a node from a Binary Tree but it failed. The program seems to be fine, however when I traversal the tree, the deleted node is still there. Why?

 BinaryTreeNode MinLeftChild(BinaryTreeNode parent)
        {
            if (parent == null)
                return null;
            if (parent.left == null)
            {
                return parent;
            }
            return MinLeftChild(parent.left);
        }

        public void DeleteNode(int num)
        {
            DeleteNode(num, this.root);
        }

        private void DeleteNode(int num, BinaryTreeNode node)
        {
            if (node == null)
                return;
            // There are three cases.
            // Case 1: If the node being deleted has no right child, then the node's left child can be used as the replacement. 
            // Case 2: If the deleted node's right child has no left child, then the deleted node's right child can replace the deleted node. 
            // Case 3: Finally, if the deleted node's right child does have a left child, then the deleted node needs to be replaced by the deleted node's right child's left-most descendant. That is, we replace the deleted node with the deleted node's right subtree's smallest value.
            if (num < node.data)
                DeleteNode(num, node.left);
            else if (num > node.data)
                DeleteNode(num, node.right);
            else if (node.left != null && node.right != null)
            {
                node.data = MinLeftChild(node.right).data;
                DeleteNode(node.data, node.right);
            }
            else
            {
                node = (node.left != null) ? node.left : node.right;
            }
        }

The BinaryTreeNode class is simple:

 public class BinaryTreeNode
    {
        public int data { get; set; }
        public BinaryTreeNode left { get; set; }
        public BinaryTreeNode right { get; set; }
        public int Height;
        public BinaryTreeNode()
        {
           // data = 0;
            left = null;
            right = null;
        }
        public BinaryTreeNode(int data)
        {
            this.data = data;
        }
    }

And the binary tree is:

 public class BinaryTree
    {
        private BinaryTreeNode root { get; set; }

        public BinaryTree(int data)
        {
            root = new BinaryTreeNode(data);
        }


Viewing all articles
Browse latest Browse all 31927

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>