본문 바로가기

TIL/이전 풀이

[js] leetcode_235. Lowest Common Ancestor of a Binary Search Tree

JS 숙련도를 위하여 JS로 별도로 풀어봤다.

 

/**
 * 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 (p.val < root.val && q.val < root.val) {
        return lowestCommonAncestor(root.left,p,q)
    }
    else if( p.val > root.val && q.val > root.val) {
        return lowestCommonAncestor(root.right,p,q)
    }
    else {
        return root
    }
};