Gasper Gulotta
Gasper Gulotta

Reputation: 159

Traversing a Binary Tree in value order in Java

My goal is to traverse a Binary Tree and find all values between 2 given values. I am trying to think of a way to go to the lowest point, than traverse the tree in order from left to right. But my code doesn't have pointers to parent nodes so that is out of the question. Is there a way to do this so that I can traverse the tree from left to right?

Upvotes: 0

Views: 389

Answers (1)

BevynQ
BevynQ

Reputation: 8269

You do not need a pointer to the parent node. The callstack can proxy it, use a recursive method call.

public void traverse(TreeNode node){
    if(node == null){
        return;
    }else {
        // display values to the left of current node
        traverse(node.left);
        // display current node
        System.out.println(node.value);
        // display values to the right of current node
        traverse(node.right);
    }
}

Upvotes: 1

Related Questions