C
C#9mo ago
mrmiyagi

simple algorithm question

FUNCTION CountX(t: Tree; x: INTEGER): INTEGER
BEGIN
IF t = NIL THEN
CountX:= 0;
ELSE IF t^.val = x THEN
CountX:= 1;
ELSE
CountX:= CountX(t^.left; x) + CountX(t^.left; x);
END;
FUNCTION CountX(t: Tree; x: INTEGER): INTEGER
BEGIN
IF t = NIL THEN
CountX:= 0;
ELSE IF t^.val = x THEN
CountX:= 1;
ELSE
CountX:= CountX(t^.left; x) + CountX(t^.left; x);
END;
Quick question: In this function lets say that the "else if" comes true in the first node. wouldnt it just skip the "else" and give out CountX = 1 ? so in order to solve that, my recursive call should not be bound by that "else" and should be done anyway (the code is pascal, but that shouldnt matter with this simple algorithm)
1 Reply
oke
oke9mo ago
chained if statements run from top to bottom, exiting with the first statement that evaluates to true
int num = 3;

if (num == 1)
{
Console.WriteLine("It's 1");
}
else if (num == 2)
{
Console.WriteLine("It's 2");
}
else
{
Console.WriteLine("It's not 1 or 2");
}

// The output would be "It's 2" because its the first expression to evaluate as True
int num = 3;

if (num == 1)
{
Console.WriteLine("It's 1");
}
else if (num == 2)
{
Console.WriteLine("It's 2");
}
else
{
Console.WriteLine("It's not 1 or 2");
}

// The output would be "It's 2" because its the first expression to evaluate as True
this is it in C#
public static int CountX(TreeNode t, int x)
{
if (t == null)
{
return 0;
}
else if (t.val == x)
{
return 1;
}
else
{
return CountX(t.left, x) + CountX(t.right, x);
}
}
public static int CountX(TreeNode t, int x)
{
if (t == null)
{
return 0;
}
else if (t.val == x)
{
return 1;
}
else
{
return CountX(t.left, x) + CountX(t.right, x);
}
}
Want results from more Discord servers?
Add your server