1

How would anyone convert a array based tree into per-order? The array contains:

Cheers

public void preOrder(int index) {

    if (index >= currSize) {
        return;
    }

    System.out.println(items[index]);
    preOrder(2 ^ index + 1); //left
    preOrder((2 ^ index) + 2); //right
}
4
  • What is the parent of 7? Please add more information. Is it like a heap where the children of the n-th element are at positions 2**n and 2**(n+1)? (Assuming indices start at 1) Commented Feb 4, 2012 at 7:17
  • 7 is a leaf, its a complete binary tree. Commented Feb 4, 2012 at 7:18
  • Its a tutorial question, not really a homework its given to test your self. i'm really interested in knowing the outcome. Commented Feb 4, 2012 at 7:21
  • @jonny: "7 is leaf" does not really answer my question, which was what is 7's parent (not 7's child). But your ASCII art diagram does, which shows 7's parent is 5. Its much clearer now. Commented Feb 4, 2012 at 7:26

2 Answers 2

2

Should be like the following.

public void preOrder(int index) {

    if (index >= currSize) {
        return;
    }
    System.out.println(items[index]);
    preOrder((2 * index)+1);
    preOrder((2 * index)+2);
 }
Sign up to request clarification or add additional context in comments.

Comments

2

In pre-order traversal, you process the parent first, then you recursively process the left subtree and right subtree. The representation that you have is basically the same as that of a heap, so it is clear what the left and right children of any node is. This means we can traverse this in pre-order and print out the nodes in the order we visit them.

Pseudo code would be as follows:

print_pre_order(index):
  if index is beyond the size of the array:
    return
  else:
    print value at index
    print_pre_order(left child of index)
    print_pre_order(right child of index)

Since this is arranged as a heap, for each index n the left child is at 2*n and the right child is at 2*(n+1). Note that I am assuming indices of the array start from 1 (though most languages have them start at 0), but you can easily adapt that for 0 based arrays.

2 Comments

i have posted the method i came up with in the main post.
@jonny: ^ is the XOR operator in Java, not exponentiation. Replace 2^n with 1<<n (shifting 1 left by n is the same as 2**n).

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.