Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

avenge avatar avenge 1 Точки

Проблем с пример от книгата Introduction-to-Programing-with-Java-Book-v2014 - BinaryTree

Здравейте

Нещо не ми се получава примера от книгата, не мога да разбера защо, всичко е както е написано там.

public class BinaryTree {
    public static class BinaryTreeNode<T> {
        private T value;
        private boolean hasParent;
        private BinaryTreeNode<T> leftChild;
        private BinaryTreeNode<T> rightChild;

        /**
         * Constructs a binary tree node.
         *
         * @param value      - the value of the node.
         * @param leftChild  - the left child of the node.
         * @param rightChild - the right child of the node.
         */
        public BinaryTreeNode(T value,
                              BinaryTreeNode<T> leftChild,
                              BinaryTreeNode<T> rightChild) {
            if (value == null) {
                throw new IllegalArgumentException(
                        "Cannot insert null value!");
            }

            this.value = value;
            this.leftChild = leftChild;
            this.rightChild = rightChild;
        }

        /**
         * Constructs a binary tree node with no children.
         *
         * @param value - the value of the node.
         */
        public BinaryTreeNode(T value) {
            this(value, null, null);
        }

        public T getValue() {
            return this.value;
        }

        public void setValue(T value) {
            this.value = value;
        }

        public BinaryTreeNode<T> getLeftChild() {
            return this.leftChild;
        }

        public void setLeftChild(BinaryTreeNode<T> value) {
            if (value == null || value.hasParent) {
                throw new IllegalArgumentException();
            }

            value.hasParent = true;
            this.leftChild = value;
        }

        public BinaryTreeNode<T> getRightChild() {
            return this.rightChild;
        }

        public void setRightChild(BinaryTreeNode<T> value) {
            if (value == null || value.hasParent) {
                throw new IllegalArgumentException();
            }

            value.hasParent = true;
            this.rightChild = value;
        }
    }

    // The root of the tree
    private BinaryTreeNode<T> root;

    /**
     * Constructs the tree.
     * @param value - the value of the node.
     * @param children - the children of the node.
     */
    public BinaryTree(T value, BinaryTree<T> leftChild,
                      BinaryTree<T> rightChild) {

        if (value == null) {
            throw new IllegalArgumentException();
        }

        BinaryTreeNode<T> leftChildNode =
                leftChild != null ? leftChild.root : null;
        BinaryTreeNode<T> rightChildNode =
                rightChild != null ? rightChild.root : null;
        this.root = new BinaryTreeNode<T>(
                value, leftChildNode, rightChildNode);
    }

    /**
     * Constructs the tree.
     * @param value - the value of the node.
     */
    public BinaryTreeNode<T> getRoot() {
        return this.root;
    }

    /**
     * @return the left child of the root.
     */
    public BinaryTreeNode<T> getLeftChildNode() {
        if (this.root != null) {
            return this.root.getLeftChild();
        }

        return null;
    }

    /**
     * Traverses binary tree in pre-order manner.
     * @param root - the binary tree to be traversed.
     */
    private void printPreOrder(BinaryTreeNode<T> root) {
        if (root == null) {
            return;
        }

        printPreOrder(root.getLeftChild());

        System.out.print(root.getValue() + " ");

        printPreOrder(root.getRightChild());
    }

    /**
     * Traverses and prints the binary
     * tree in pre-order manner.
     */
    public void printPreOrder() {
        printPreOrder(this.root);
        System.out.println();
    }
}

public class BinaryTreeExample {
    public static void main(String[] args) {
// Create the binary tree from the sample.
        BinaryTree<Integer> binaryTree =
                new BinaryTree<Integer>(14,
                        new BinaryTree<Integer>(19,
                                new BinaryTree<Integer>(23),
                                new BinaryTree<Integer>(6,
                                        new BinaryTree<Integer>(10),
                                        new BinaryTree<Integer>(21))),
                        new BinaryTree<Integer>(15,
                                new BinaryTree<Integer>(3),
                                null));
// Traverse and print the tree in pre-order manner.
        binaryTree.printPreOrder();
    }
}

За "BinaryTree" IntelliJ ми дава след "//The root of the tree" - "Cannot resolve symbol "T" и ми дава "Т" в червено. Не мога да разбера защо тази част е извън класа, където е дефинирано "Т". Ако го вкарам вътре се омазва още повече.

За "BinaryTreeExample" ми изкарва на "Integer" че няма такъв тип параметър и дава и грешки при компилиране и опит за изпълнение. Къде е проблема, или примера си е грешно  даден?

Тагове:
0
Module: Java Advanced 31/07/2017 18:39:52
avenge avatar avenge 1 Точки

Нещо съм преписал грешно, направих copy/paste и всичко работи :)

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.