Sunday, November 8, 2015

Find all Root to Leaf Path of a Binary Tree

 This program uses the Binary Search Tree program available here: link
The same program can also be used for Binary Tree

    public void FindAllRoot2LeefPath()    {
        ArrList = new ArrayList<CustomLinkedList>();
        FindAllRoot2LeefPath(this, new ArrayList<Integer>());
        for(CustomLinkedList L:ArrList)    {
            L.printList();
        }
    }
   
    public ArrayList<CustomLinkedList> ArrList;
   
    private ArrayList<Integer> FindAllRoot2LeefPath(BinarySearchTree T, ArrayList<Integer> path)    {
        if(T!=null){
            path.add(T.data);
            if(T.left==null && T.right==null)    {
                CustomLinkedList L = new CustomLinkedList(path.get(0));
                L.appendList(path);
                ArrList.add(L);
                System.out.println(path);
            }    else    {
                FindAllRoot2LeefPath(T.left, new ArrayList<>(path));
                FindAllRoot2LeefPath(T.right, new ArrayList<>(path));
            }
        }
        return path;
    }
/*-----------------------------------------------------------------------------------------------*/
CustomLinkedList is a program given here: link
I added one more method there for this:

    public void appendList(ArrayList<Integer> ArrList)    {
        int size = ArrList.size();
        /*Starts from i=1 because
         * Head Element already need to be added when creating a new list*/
        for(int i=1;i<size;i++)    {
            append(ArrList.get(i));           
        }
    }

No comments:

Post a Comment

UA-39217154-2