IBM Interview Question
Software Engineer / DevelopersHere is my code in C#.
A list is used to store the leaf node (which finally becomes roots).
Based on Post-Order traversal and it works.
May be you can add code to make initial root.left = root.right = null.
I tested and it works :)
public List<node> list = null;
public void Reverse()
{
list = new List<node>();
ReverseTree(root, null);
}
private void ReverseTree(node rootptr,node rootroot)
{
node temp;
if (rootptr.left != null)
{
ReverseTree(rootptr.left,rootptr);
}
if (rootptr.right != null)
{
ReverseTree(rootptr.right,rootptr);
}
if ((rootptr.left == null) && (rootptr.right == null))
{
list.Add(rootptr);
}
if (rootroot != null)
rootptr.left = rootroot;
}
- knap August 14, 2009