-
LeetCode : 98. Validate Binary Search Tree๐ณDev/LeetCode 2023. 5. 3. 21:42
๋ฌธ์
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
- The left of a node contains only nodes with keys less than the node's key.
- subtree
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
Constraints:
- The number of nodes in the tree is in the range [1, 104].
- 231 <= Node.val <= 231 - 1
ํ์ด
- ์ด์ง ํธ๋ฆฌ์ ๋ ธ๋ ๊ฐ์ ํญ์ ์ ํด์ง ๋ฒ์๊ฐ ์์ผ๋ฏ๋ก ์ด๋ฅผ ์ฌ์ฉํจ
- ๋ ธ๋๊ฐ None์ธ ๊ฒฝ์ฐ์๋ True๋ก ์ข ๋ฃ
- ๋ฒ์์ ๋ถํฉํ์ง ์๋ ๊ฒฝ์ฐ์๋ False๋ก ์ข ๋ฃ
- ์ด์ง ํธ๋ฆฌ์ด๋ฏ๋ก, ์์ชฝ ๋ ธ๋๊ฐ ์ ๋ถ ์กฐ๊ฑด์ ๋ถํฉํด์ผ ์ฆ False๊ฐ ํ๋๋ผ๋ ์์ด์ผ ํจ
์์)
- min_c = ๋ฌดํ์ผ๋ก ์ด๊ธฐํ, max_c = ๋ฌดํ์ผ๋ก ์ด๊ธฐํ
- ์ฒ์ root(5)์ ์ผ์ชฝ์ ์์ ๋
ธ๋(1)๋ ๋จ์ํ root(5)๋ณด๋ค ์์ ๊ฐ์ ๊ฐ์ ธ์ผ ํจ
- ๋ ธ๋(1)์ ๋ฒ์ : min_c = ์ต์๊ฐ(์ ์ง), max_c = ๋ถ๋ชจ ๊ฐ์ธ 5๋ก ๋ณ๊ฒฝ
- ์ฒ์ root(5)์ ์ค๋ฅธ์ชฝ ์์ ๋
ธ๋(7)๋ ํฐ ๊ฐ์ ๊ฐ์ ธ์ผ ํจ
- ๋ ธ๋(7)์ ๋ฒ์ : min_c = ๋ถ๋ชจ ๊ฐ์ธ 5๋ก ๋ณ๊ฒฝ, max_c = ์ต๋๊ฐ(์ ์ง)
- ๋
ธ๋(7)์ ์ค๋ฅธ์ชฝ ์์ ๋
ธ๋(8)๋ ๋ถ๋ชจ(7)๋ณด๋ค ํฐ ๊ฐ์ ๊ฐ์ ธ์ผ ํจ
- ๋ ธ๋(8)์ ๋ฒ์ : min_c = ๋ถ๋ชจ ๊ฐ์ธ 7๋ก ๋ณ๊ฒฝ, max_c = ์ ์ง(์ต๋๊ฐ)
- ๋
ธ๋(7)์ ์ผ์ชฝ ์์ ๋
ธ๋(6)๋ ์ต์๊ฐ์ธ ๋
ธ๋(5)๋ณด๋ค๋ ํฌ๊ณ ๋ถ๋ชจ(7)๋ณด๋ค ์์ ๊ฐ์ ๊ฐ์ ธ์ผ ํจ
- ๋ ธ๋(6)์ ๋ฒ์ : min_c = 5(์ ์ง), max_c = ๋ถ๋ชจ ๊ฐ์ธ 7๋ก ๋ณ๊ฒฝ
๋ฐ๋ผ์, right.val๋ ์ต์ node.val๊ณผ ์ต๋ max์ ๋ฒ์๋ฅผ ๊ฐ์ง๊ณ , left.val์ ์ต์ min, ์ต๋ node.val์ ๋ฒ์๋ฅผ ๊ฐ์ง
'๐ณDev > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
LeetCode : 1484. Group Sold Products By The Date (0) 2023.05.13 LeetCode : 200. Number of Islands (0) 2023.05.08 LeetCode : 235.ย Lowest Common Ancestor of a Binary Search Tree (0) 2023.05.05 LeetCode : 102. Binary Tree Level Order Traversal (0) 2023.05.01 LeetCode : 142. Linked List Cycle II (0) 2023.04.26