1

How to write a correct inorder-method for my binary-tree implementation?

This is my test-try:

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));
        }
    }
}
2
  • 1
    Love to help what are you trying to do here Commented May 4, 2015 at 19:18
  • Can you post what your problem is exactly? What's wrong? What's the expected output? Commented May 5, 2015 at 0:31

1 Answer 1

1

myTree.inorder(0); // parameter : 0

inorder((node * 2)); // node = 0, node * 2 = 0,

Therefore, the parameters will continue to be zero is an infinite loop.

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.