Wednesday, January 21, 2015

Binary Tree Fun

Let's parse this sucker without recursion.

(function () {
    'use strict';

    var Node = function (text, left, right) {
        this.text = text;
        this.left = left;
        this.right = right;
    };

    Node.prototype.print = function (vertical, direction) {
        var node = this;
        var queueOrStack = [this];
        direction = direction || 'right';

        do {
            node = queueOrStack[vertical ? 'pop' : 'shift']();

            if (node) {
                console.log(node.text);

                queueOrStack.push(node[direction === 'left' ? 'right' : 'left']);
                queueOrStack.push(node[direction]);
            }
        } while (queueOrStack.length);
    };

    var n0 = new Node(0);
    var n2 = new Node(2);
    var n1 = new Node(1, n0, n2);
    var n5 = new Node(5);
    var n4 = new Node(4, null, n5);
    var n6 = new Node(6, n4);
    var n3 = new Node(3, n1, n6);
    var n8 = new Node(8);
    var n10 = new Node(10);
    var n11 = new Node(11, n10);
    var n9 = new Node(9, n8, n11);
    var n14 = new Node(14);
    var n15 = new Node(15, n14);
    var n13 = new Node(13, null, n15);
    var n12 = new Node(12, n9, n13);
    var n7 = new Node(7, n3, n12);

    n7.print();
    // 7, 3, 12, 1, 6, 9, 13, 0, 2, 4, 8, 11, 15, 5, 10, 14

    n7.print(true);
    // 7, 12, 13, 15, 14, 9, 11, 10, 8, 3, 6, 4, 5, 1, 2, 0

    n7.print(true, 'left');
    // 7, 3, 1, 0, 2, 6, 4, 5, 12, 9, 8, 11, 10, 13, 15, 14

    n7.print(false, 'left');
    // 7, 12, 3, 13, 9, 6, 1, 15, 11, 8, 4, 2, 0, 14, 10, 5
}());

No comments:

Post a Comment