3

This question is from the book Introduction to Algorithms 3rd:

**Each node in the binary tree has 4 properties: key,left,right,parent

EDIT: The binary tree is stored as linked nodes that each one of them has the 4 properties I mentioned.

Write an O(n) time nonrecursive procedure that, given an n-node binary tree, prints out the key of each node. Use no more than constant extra space outside of the tree itself and do not modify the tree, even temporarily, during the procedure.

I tried to find a solution but got nothing...(Also I searched google for solutions for this book, but this question wasn't included there maybe because it was added in later versions).

2
  • you may want to check out this: stackoverflow.com/questions/5502916/…. Commented Aug 20, 2014 at 11:28
  • 1
    @dguan this algorithm modify the tree during the procedure. Commented Aug 20, 2014 at 11:40

1 Answer 1

4

Here's a solution:

  • Let current store the currently visited node (initialized to the root of the tree)
  • Let origin represent how we got to the current node. It's one of FROM_PARENT, FROM_LEFT_CHILD, FROM_RIGHT_CHILD. (Initialized to FROM_PARENT)

Algorithm:

  • If we came from the top, we print the key and go down left
  • If we came back from left, go down right
  • If we came back form right, go up.

 

origin = FROM_PARENT;
current = root;

while (current != null) {

    switch (origin) {

    case FROM_PARENT:
        System.out.println(current.key);
        if (current.left != null)
            goLeft();
        else
            origin = FROM_LEFT_CHILD;
        break;

    case FROM_LEFT_CHILD:
        if (current.right != null)
            goRight();
        else
            origin = FROM_RIGHT_CHILD;
        break;

    case FROM_RIGHT_CHILD:
        goToParent();
        break;
    }            
}

Where

static void goToParent() {
    if (current.parent == null) {
        current = null;
        return;
    }
    origin = current == current.parent.left ? FROM_LEFT_CHILD
                                            : FROM_RIGHT_CHILD;
    current = current.parent;
}

static void goLeft() {
    origin = FROM_PARENT;
    current = current.left;
}

static void goRight() {
    origin = FROM_PARENT;
    current = current.right;
}
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.