Clay
Clay

Reputation: 65

Returning a Tree Inorder Traversal Results

I am new to Javascript. Below I have a code that uses inorder traversal method to recursively traverse my tree and print the result using document.write. My question is instead of printing the result, I just want to return the result for further use. How can I do it?

function inOrder(node) {
    if (!(node == null)) {
        inOrder(node.left);
        document.write(node.toString());
        inOrder(node.right);
    }
}

Thank you for helping. Much appreciated =)

Upvotes: 5

Views: 1788

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386578

You could use an array for the result

function getAllNodes(node) {

    function inOrder(node) {
        if (node) {
            inOrder(node.left);
            result.push(node.toString()); // push instead of output.
            inOrder(node.right);
        }
    }

    var result = [];
    inOrder(node);
    return result;
}

Another solution is to add a parameter to the function and collect the result in an array.

function inOrder(node, result) {
    if (node) {
        inOrder(node.left, result);
        result.push(node.toString());
        inOrder(node.right, result);
    }
}

var result = [];
inOrder(node, result);

For result as a string

function getAllNodes(node) {

    function inOrder(node) {
        if (node) {
            inOrder(node.left);
            result += node.toString() + ', ';
            inOrder(node.right);
        }
    }

    var result = '';
    inOrder(node);
    return result;
}

Upvotes: 5

Related Questions