Skip to Content
C# Data Structures and Algorithms
book

C# Data Structures and Algorithms

by Marcin Jamro
April 2018
Intermediate to advanced content levelIntermediate to advanced
292 pages
6h 44m
English
Packt Publishing
Content preview from C# Data Structures and Algorithms

Insertion

The next necessary operation is insertion of a node into a BST. Such a task is a bit more complicated, because you need to find a place for adding a new element that will not violate the BST rules. Let's take a look at the code of the Add method:

public void Add(T data) 
{ 
    BinaryTreeNode<T> parent = GetParentForNewNode(data); 
    BinaryTreeNode<T> node = new BinaryTreeNode<T>()  
        { Data = data, Parent = parent }; 
 
    if (parent == null) 
    { 
        Root = node; 
    } 
    else if (data.CompareTo(parent.Data) < 0) 
    { 
        parent.Left = node; 
    } 
    else 
    { 
        parent.Right = node; 
    } 
 
    Count++; 
} 

The method takes one parameter, a value that should be added to the tree. Within the method, you find a parent element (using the GetParentForNewNode auxiliary method), where a new node ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Beginning Data Structures and Algorithms in C#

Beginning Data Structures and Algorithms in C#

Marcin Jamro

Publisher Resources

ISBN: 9781788833738Supplemental Content