/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function(root, p, q) {
    // if one is lower and one is higher than the current root val, then root is the LCA
    // then it is just order, if encounter one then it is the LCA of the two
    
    let queue = new Array()
    queue.push(root)
    while (queue.length > 0) {
        let node = queue.shift()
        if (((node.val > p.val) && (node.val < q.val)) || 
            ((node.val < p.val && node.val > p.val))) {
            return node
        } else if (node.val > p.val && node.val > q.val) {
            queue.push(node.left)
        } else if (node.val < p.val && node.val < q.val) {
            queue.push(node.right)
        } else {
            // is equal
            return node
        }
    }
    return root
};