๋ฌธ์
ํ์ด ๊ณผ์
์
๋ ฅ์ผ๋ก ์ฃผ์ด์ง ํธ๋ฆฌ๊ฐ ์ด์ง ๊ฒ์ ํธ๋ฆฌ
์ ์๊ตฌ ์ฌํญ์ ๋ง๋ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๊ณ ์๋์ง ํ๋จํ๋ ๋ฌธ์ ์
๋๋ค. ์ด์ง ๊ฒ์ ํธ๋ฆฌ
๋ ๋ฃจํธ ๋
ธ๋๊ฐ ์ผ์ชฝ ์๋ธํธ๋ฆฌ์ ๋ชจ๋ ๋
ธ๋๋ณด๋ค ์ปค์ผํ๊ณ ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ์ ๋ชจ๋ ๋
ธ๋๋ณด๋ค ์์์ผํฉ๋๋ค.
๋ฐ๋ผ์ 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;
};
๋ฐ์ํ
'๐ algorithm > leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
LeetCode 102 - Binary Tree Level Order Traversal (Medium) (0) | 2021.03.03 |
---|---|
LeetCode 617 - Merge Two Binary Trees (Easy) (0) | 2021.03.03 |
LeetCode 130 - Surrounded Regions (Medium) (0) | 2021.03.03 |
LeetCode 226 - Invert Binary Tree (Easy) (0) | 2021.03.03 |
LeetCode 406 - Queue Reconstruction by Height (Medium) (0) | 2021.03.03 |
๐ฌ ๋๊ธ