Q. Create a linked list to hold each level of the binary tree. Then store the linked list headers in an array.
Algorithm.
1. Create a linked list array as an instance variable.
2. Create a preorder traversal like recursive function.
3. The function takes the level as a parameter and increments it before
passing it to the next recursive call.
4. Add the root element to the linked list stored at listarray[level].
5. make a recursive call with the left subtree and right subtree.
A working Java implementation is given below.
package lab.tree;
import lab.linkedlist.*;
public class SpecialTree extends Tree {
LinkedList[] listarray=new LinkedList[100];
public void treeToListArray(TreeNode rootnode,int level)
{
if(rootnode !=null)
{
if (listarray[level]==null)
{
LinkedList tmplist=new LinkedList();
tmplist.insertBegining(rootnode.data);
listarray[level]= tmplist;
level++;
}
else
{
listarray[level].insertBegining(rootnode.data);
level++;
}
treeToListArray(rootnode.left,level);
treeToListArray(rootnode.right,level);
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment