지식의모듈화

[LeetCode][Javascript] Binary Search Tree Problems 본문

PS/LeetCode

[LeetCode][Javascript] Binary Search Tree Problems

returnzero 2022. 8. 4. 21:03

98. Validate Binary Search Tree

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
 
var isValidBST = function(root) {
    // console.log(root.left, root.right, root, "VALID");
    let arr=[];
    let ans=true;
    function DFS(current){
        if(current==null)return;
        DFS(current.left);
        // console.log(current.val);
        arr.push(current.val);
        DFS(current.right);
    }
    DFS(root)
    // console.log(arr);
    for(let i=0; i<arr.length-1; i++){
        if(arr[i]>= arr[i+1]) ans=false;
    }
    return ans;
};

O(N) solution, time complexity 개선 가능하다.

 

104. Maximum Depth of Binary Tree

var maxDepth = function(root) {
    if(!root) return 0;
    return Math.max(maxDepth(root.right)+1, maxDepth(root.left)+1)
};

 

230. Kth Smallest Element in a BST

var kthSmallest = function(root, k) {
    let arr=[];
    function DFS(current){
        if (current==null) return;
        DFS(current.left)
        // console.log(current.val);
        arr.push(current.val)
        DFS(current.right)
    }
    DFS(root);
    // console.log(arr);
    return arr[k-1];
};

 O(N)으로, time complexity개선 가능하다.