尝试将二进制搜索树转换为数组(返回Null)

问题描述 投票:0回答:2

我想将我的二进制搜索树转换为数组(使用顺序遍历)。

为此,我有3种方法。

问题:方法1 System.out.print()调用中的java.lang.NullPointerException。但是成功返回4个元素(2个为null,因此会出现此错误,但为什么呢?!)

类(1个主要方法)1(调用方法)

 public void top() {
    array[] unsortedList = this.bookList.returnBSTAsArray(6); // 6 is the number of nodes in tree
     for (Book book: unsortedList) {
         System.out.println("--> Title: " + book.title());
     }

[class(2)方法2

// traverse BST in order and return an array of books 
public Book[] returnBSTAsArray(int totalLength) {
    Book[] list = new Book[totalLength];
    int index = 0;

    storeInOrder(this.root, list, index);  // root is node accessible to this class

    return list;
}

Class(2)方法3-进行顺序遍历的有趣方法

 private Book[] storeInOrder(Node root, Book[] array, int index) {
        if (root == null)
            return null;
        storeInOrder(root.leftChild, array, index);
        array[index++] = root.movie;
        storeInOrder(root.rightChild, array, index);

        return array;
    }
java arrays binary-search-tree binary-search inorder
2个回答
0
投票

您可以通过跟踪每个元素的索引来使用完成,将其添加回结果数组中>]

  static class BST {

        private class Node {
            private Integer key;
            private Node left, right;
            private int index;

            public Node(Integer key, int index) {
                this.key = key;
                this.index = index;
            }
        }

        private Node root;
        private int size = 0;

        public void put(int[] arr) {
            if (size >= arr.length)
                return;
            root = put(root, arr[size], size);
            size++;
            put(arr);
        }

        private Node put(Node node, int key, int index) {
            if (node == null)
                return new Node(key, index);
            int cmp = Integer.valueOf(key).compareTo(node.key);
            if (cmp < 0)
                node.left = put(node.left, key, index);
            else if (cmp > 0)
                node.right = put(node.right, key, index);
            else
                node.key = key;
            return node;
        }

        public int size() {
            return size;
        }

        public int[] keys() {
            int[] result = new int[size];
            get(root, result, 0);
            return result;
        }

        public void get(Node node, int[] result, int i) {
            if (i >= result.length || node == null)
                return;
            result[node.index] = node.key;
            get(node.left, result, ++i);
            get(node.right, result, ++i);
        }
    }

,主要

    public static void main(String[] args) {
        BST bst = new BST();
        bst.put(new int[] { 10, 20, 5, 40, 1, 60, -10, 0 });

        for (int num : bst.keys()) {
            System.out.print(num + " ");
        }
    }

,输出

10 20 5 40 1 60

0
投票

Java是一种“传递价值”的语言。因此(通常来说),调用者将看不到对函数中参数值的任何更改。

© www.soinside.com 2019 - 2024. All rights reserved.