ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 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).

    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

     

    ํ’€์ด

    • ์ด์ง„ ํŠธ๋ฆฌ์˜ ๋…ธ๋“œ ๊ฐ’์€ ํ•ญ์ƒ ์ •ํ•ด์ง„ ๋ฒ”์œ„๊ฐ€ ์žˆ์œผ๋ฏ€๋กœ ์ด๋ฅผ ์‚ฌ์šฉํ•จ
    1. ๋…ธ๋“œ๊ฐ€ None์ธ ๊ฒฝ์šฐ์—๋Š” True๋กœ ์ข…๋ฃŒ
    2. ๋ฒ”์œ„์— ๋ถ€ํ•ฉํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ์—๋Š” False๋กœ ์ข…๋ฃŒ
    3. ์ด์ง„ ํŠธ๋ฆฌ์ด๋ฏ€๋กœ, ์–‘์ชฝ ๋…ธ๋“œ๊ฐ€ ์ „๋ถ€ ์กฐ๊ฑด์— ๋ถ€ํ•ฉํ•ด์•ผ ์ฆ‰ False๊ฐ€ ํ•˜๋‚˜๋ผ๋„ ์—†์–ด์•ผ ํ•จ

     

    ์˜ˆ์‹œ)

    • min_c = ๋ฌดํ•œ์œผ๋กœ ์ดˆ๊ธฐํ™”, max_c = ๋ฌดํ•œ์œผ๋กœ ์ดˆ๊ธฐํ™”
    1. ์ฒ˜์Œ root(5)์˜ ์™ผ์ชฝ์˜ ์ž์‹ ๋…ธ๋“œ(1)๋Š” ๋‹จ์ˆœํžˆ root(5)๋ณด๋‹ค ์ž‘์€ ๊ฐ’์„ ๊ฐ€์ ธ์•ผ ํ•จ
      • ๋…ธ๋“œ(1)์˜ ๋ฒ”์œ„ : min_c = ์ตœ์†Œ๊ฐ’(์œ ์ง€), max_c = ๋ถ€๋ชจ ๊ฐ’์ธ 5๋กœ ๋ณ€๊ฒฝ
    2. ์ฒ˜์Œ root(5)์˜ ์˜ค๋ฅธ์ชฝ ์ž์‹ ๋…ธ๋“œ(7)๋Š” ํฐ ๊ฐ’์„ ๊ฐ€์ ธ์•ผ ํ•จ
      • ๋…ธ๋“œ(7)์˜ ๋ฒ”์œ„ : min_c = ๋ถ€๋ชจ ๊ฐ’์ธ 5๋กœ ๋ณ€๊ฒฝ, max_c = ์ตœ๋Œ€๊ฐ’(์œ ์ง€)
    3. ๋…ธ๋“œ(7)์˜ ์˜ค๋ฅธ์ชฝ ์ž์‹ ๋…ธ๋“œ(8)๋Š” ๋ถ€๋ชจ(7)๋ณด๋‹ค ํฐ ๊ฐ’์„ ๊ฐ€์ ธ์•ผ ํ•จ
      • ๋…ธ๋“œ(8)์˜ ๋ฒ”์œ„ : min_c = ๋ถ€๋ชจ ๊ฐ’์ธ 7๋กœ ๋ณ€๊ฒฝ, max_c = ์œ ์ง€(์ตœ๋Œ€๊ฐ’)
    4. ๋…ธ๋“œ(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
Designed by Tistory.