1

二分木実装の正しい inorder-method を書く方法は?

これは私のテストトライです:

class Main {
    public static void main(String[] args) {
        BinaryTree myTree = new BinaryTree();
        myTree.inorder(0);
    } 
}

public class BinaryTree {
    char[] tree = {'k', 'q', 'r', 'g', 'e', 'i', 'y', 'p', 'l', 'b', 'x', 'm', 'g', 't', 'u', 'v', 'z'};
    public void inorder(int node) {
        if(node < tree.length) {
            inorder((node * 2));
            System.out.print(tree[node] + " ");
            inorder(((node * 2) + 1));
        }
    }
}
4

1 に答える 1

1

myTree.inorder(0); // パラメータ: 0

inorder((ノード * 2)); // ノード = 0、ノード * 2 = 0、

したがって、パラメータはゼロであり続け、無限ループになります。

public class BinaryTree {
    char[] tree = {'k', 'q', 'r', 'g', 'e', 'i', 'y', 'p', 'l', 'b', 'x', 'm', 'g', 't', 'u', 'v', 'z'};
    public void inorder(int node) {
        if(node < tree.length) {
            inorder((node * 2) + 1);
            System.out.print(tree[node] + " ");
            inorder(((node * 2) + 2));
        }
    }


    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        tree.inorder(0);
    }
}
于 2015-05-04T20:00:35.517 に答える