๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 98 - Validate Binary Search Tree (Medium)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 98๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„ ํŠธ๋ฆฌ๊ฐ€ ์ด์ง„ ๊ฒ€์ƒ‰ ํŠธ๋ฆฌ ์˜ ์š”๊ตฌ ์‚ฌํ•ญ์— ๋งž๋Š” ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”์ง€ ํŒ๋‹จํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์ด์ง„ ๊ฒ€์ƒ‰ ํŠธ๋ฆฌ ๋Š” ๋ฃจํŠธ ๋…ธ๋“œ๊ฐ€ ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๋…ธ๋“œ๋ณด๋‹ค ์ปค์•ผํ•˜๊ณ  ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๋…ธ๋“œ๋ณด๋‹ค ์ž‘์•„์•ผํ•ฉ๋‹ˆ๋‹ค.
๋”ฐ๋ผ์„œ minMax ๋ผ๋Š” ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด DFS ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋ฉฐ ํ˜„์žฌ ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ๊ธฐ์ค€์œผ๋กœ
ํ•ด๋‹น ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’๊ณผ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ํ•ฉ๋‹ˆ๋‹ค.

๊ทธ๋Ÿฐ๋ฐ ๋‹ค ํ’€๊ณ ๋‚˜์„œ ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์˜ ํ’€์ด๋ฒ•์„ ๋ณด๋‹ˆ ๊ทธ๋ƒฅ ์ค‘์œ„ ์ˆœํšŒ ๋ฅผ ํ•œ ๋‹ค์Œ
์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋˜์–ด์žˆ๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ๋” ๊ตฌํ˜„ํ•˜๊ธฐ ์‰ฝ๊ณ  ๋ช…ํ™•ํ•œ ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * 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) {
  let satisfied = true;

  function minMax(root) {
    if (!root) return [null, null];

    const [leftMin, leftMax] = minMax(root.left);
    const [rightMin, rightMax] = minMax(root.right);

    if (leftMax && leftMax >= root.val) {
      satisfied = false;
    }

    if (rightMin && root.val >= rightMin) {
      satisfied = false;
    }

    const minValue = leftMin || root.val;
    const maxValue = rightMax || root.val;

    return [minValue, maxValue];
  }

  minMax(root);

  return satisfied;
};
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€