HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Generic binary tree in C#

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
genericbinarytree

Problem

This is a simple implementation of a generic binary tree that holds elements of type T. I was wondering if there was something that could be done better (especially in the EnumerateNodes methods).

```
using System.Collections.Generic;

namespace DataStructures.Node
{
///
/// Implements a generic binary tree.
///
/// The type of the nodes
public class Node
{
#region Private attributes
private T _node = default(T);
private Node _leftChild = default(Node);
private Node _rightChild = default(Node);
#endregion

#region Constructor
public Node()
{
_node = default(T);
_leftChild = null;
_rightChild = null;
}

public Node(T node)
{
_node = node;
_leftChild = null;
_rightChild = null;
}
#endregion

#region Accessors
public T Value
{
get { return _node; }
set { _node = value; }
}

public Node LeftChild
{
get { return _leftChild; }
set { _leftChild = value; }
}

public Node RightChild
{
get { return _rightChild; }
set { _rightChild = value; }
}

///
/// Returns the total number of elements in the tree.
///
public int Count
{
get { return count(); }
}
#endregion

#region Private methods

private int count()
{
if (_leftChild == null && _rightChild == null)
return 1;
if (_leftChild == null)
return 1 + _rightChild.count();
if (_rightChild == null)
return 1 + _leftChild.count();
else
return 1 + _leftChild.count() + _rightChild.count();
}

#endregion

#region Public methods

///
/// Adds the

Solution

Here's an alternative way to write count(). It's shorter and uses expressions instead of statements. You can't do as much in an expression, so I use them instead of statements when possible because there's a lower chance of things going wrong. Readability is more important than those things, though, so I recommend using what is most readable to you.

private int count()
{
    return 1 +
        (_leftChild != null ? _leftChild.count() : 0) +
        (_rightChild != null ? _rightChild.count() : 0);
}


Or if you want to use C# 6 null checking:

private int count()
{
    return 1 + (_leftChild?.count() ?? 0) + (_rightChild?.count() ?? 0);
}


Method names should be UpperCamelCase, so count() should be Count(). I'm guessing you want to access a child's Count property instead of the method because the method is private.

Code Snippets

private int count()
{
    return 1 +
        (_leftChild != null ? _leftChild.count() : 0) +
        (_rightChild != null ? _rightChild.count() : 0);
}
private int count()
{
    return 1 + (_leftChild?.count() ?? 0) + (_rightChild?.count() ?? 0);
}

Context

StackExchange Code Review Q#132560, answer score: 5

Revisions (0)

No revisions yet.