...

/

Solution Review: Finding Nodes at "k" Distance From the Root

Solution Review: Finding Nodes at "k" Distance From the Root

Finding a detailed analysis of the different ways to solve the “Finding Nodes at "K" Distance From the Root” challenge.

We'll cover the following...

Solution: Using recursion

Press + to interact
main.cs
BST.cs
using System;
namespace chapter_6
{
class Solution
{
//Helper recursive function to traverse tree and append all the nodes
// at k distance into result string
static void findK(Node root, int k, ref string result)
{
if (root == null)
return;
if (k == 0)
{
result = result + root.value.ToString() + ",";
}
else
{
//Decrement k at each step till you reach at the leaf node
// or when k == 0 then append the Node's data into result string
findK(root.leftChild, k - 1, ref result);
findK(root.rightChild, k - 1, ref result);
}
}
static string findKNodes(Node root, int k)
{
string result = string.Empty;
findK(root, k, ref result);
return result;
}
static void Main(string[] args)
{
BinarySearchTree BST = new BinarySearchTree(6);
BST.insertBST(4);
BST.insertBST(9);
BST.insertBST(5);
BST.insertBST(2);
BST.insertBST(8);
BST.insertBST(12);
Console.WriteLine(findKNodes(BST.getRoot(), 2));
}
}
}

The ...