如何将BST的所有数据存储到数组列表中?

时间:2015-05-10 13:25:13

标签: java list 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;

}

我知道不会工作,但这就是我所做的。有人可以向我解释如何正确地做到这一点吗?

提前致谢

2 个答案:

答案 0 :(得分:2)

您可以通过recursive实现此目标。

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));
    }

}

答案 1 :(得分:0)

public class TreeToArrayList {
    public static void main(String[] args) {
        int[] a = { 15, 10, 20, 8, 12, 16, 25 };
        Node root = null;
        for (int aa : a) {
            root = insert(root, aa);
        }
        List<Integer> list = new ArrayList<>();

        System.out.println(treetoArrayList(root, list));

    }

    private static List<Integer> treetoArrayList(Node root, List<Integer> list) {
        if (root == null)
            return list;
        treetoArrayList(root.left, list);
        list.add(root.data);
        treetoArrayList(root.right, list);
        return list;

    }

    private static Node insert(Node root, int data) {
        if (root == null) {
            return new Node(data);

        }

        if (data < root.data) {
            root.left = insert(root.left, data);
        }
        if (data > root.data) {
            root.right = insert(root.right, data);
        }

        return root;
    }

//Data structure to store a Binary Search Tree node
    static class Node {
        int data;
        Node left = null, right = null;

        Node(int data) {
            this.data = data;
        }
    }
}