The Following function is supposed to calculate the maximum depth or height of a Binary tree the number of nodes along the longest path from the root node down to the farthest leaf node.
please comment as if it was a 15 minute coding interview. coding style and efficiency.
this was given to you
public class BinaryTreeNode
{
public BinaryTreeNode Left { get; set; }
public BinaryTreeNode Right { get; set; }
public int Value { get; set; }
}
please comment on the unit tests as well.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TreeQuestions
{
[TestClass]
public class MaxTreeDepth
{
// 0
// 1 2
// 3
[TestMethod]
public void GetMaxTreeDepthTest()
{
BinaryTreeNode root = new BinaryTreeNode
{
Value = 0,
Left = new BinaryTreeNode {Value = 1},
Right = new BinaryTreeNode {Value = 2}
};
root.Left.Right = new BinaryTreeNode {Value = 3};
int result = GetMaxTreeDepth(root);
Assert.AreEqual(3,result);
}
// 0
[TestMethod]
public void GetMaxTreeDepthTestOneNode()
{
BinaryTreeNode root = new BinaryTreeNode
{
Value = 0,
};
int result = GetMaxTreeDepth(root);
Assert.AreEqual(1, result);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void GetMaxTreeDepthTestNull()
{
BinaryTreeNode root = null;
int result = GetMaxTreeDepth(root);
}
private int GetMaxTreeDepth(BinaryTreeNode root)
{
if (root == null)
{
throw new ArgumentNullException();
}
int depth = 0;
return GetMaxHelper(root, depth);
}
private int GetMaxHelper(BinaryTreeNode root, int depth)
{
if (root == null)
{
return depth;
}
return Math.Max( GetMaxHelper(root.Right, depth+1), GetMaxHelper(root.Left, depth+1));
}
}
}