Search code examples
javalistbinary-search-tree

How to store all the data of BST into an array list?


Like the question says Im trying to make an array list which has all the data in each of the nodes in a binary search tree.

    public List storeKeyValues(){

    List keyvalues = new ArrayList();
    boolean notdone = false;
    temp = root;

    if(temp == null){
        return null;
    }

    else{
        list.add(temp.data);
        while(!notdone){


            while(temp.left != null){

                list.add(temp.data);

                temp = temp.left;
            }


        }


    }


    return keyvalues;

}

I know that wont work but that is what i have done. Can someone explain to me how to do it correctly?

Thanks in advance


Solution

  • You can achieve this with recursion.

    public class TreeNodeDemo {
    
        List<Integer> values = new ArrayList<Integer>();
    
        public List<Integer> storeKeyValues(TreeNode root) {
            treeTravel(root);
            return values;
        }
    
        private void treeTravel(TreeNode node) {
            if (node != null) {
                treeTravel(node.left);
                values.add(node.value);
                treeTravel(node.right);
            }
        }
    
        public static void main(String args[]) {
            TreeNode root = new TreeNode(4);
            root.left = new TreeNode(2);
            root.right = new TreeNode(5);
    
            System.out.println(new TreeNodeDemo().storeKeyValues(root));
        }
    
    }