Hello I came across a question in an interview which states as follows and I have to write another version of this using the instructions. I got confused as to how:
void Foo(TreeNode root)
{
Stack nodes = new Stack();
nodes.Push(root);
while (nodes.Count > 0)
{
TreeNode node = (TreeNode) nodes.Pop();
Console.WriteLine(node.Text);
for (int i = node.Nodes.Count - 1; i >= 0; i--)
nodes.Push(node.Nodes[i]);
}
}
This is the diagram do not use stack class. Write a shorter and better solution to achieve this. start with
void Foo(TreeNode root)
{
}
---------------------------------------------------------------------------------
I managed to do it like below but do not knowhow to write using void Foo(TreeNode root)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PleasantSoln
{
public class Program
{
List<string> Treenode = new List<string>();
public static void Main()
{
List<string> Treenode = new List<string>();
Treenode.Add("Root");
Treenode.Add("Trunk");
Treenode.Add("Branches");
Treenode.Add("Leaves");
Console.WriteLine();
foreach (string node in Treenode)
{
Console.WriteLine(node);
}
Treenode.Reverse();
Console.WriteLine();
foreach (string node in Treenode)
{
Console.WriteLine(node);
}
Treenode.Reverse(1, 3);
Console.WriteLine();
foreach (string node in Treenode)
{
Console.WriteLine(node);
Console.ReadKey();
}
}
}
}