[700] Search in a Binary Search Tree | Leetcode Easy

yoongyumยท2022๋…„ 4์›” 14์ผ
0

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ๐Ÿงฉ

๋ชฉ๋ก ๋ณด๊ธฐ
12/47
post-thumbnail

๐Ÿ”Ž ๋ฌธ์ œ์„ค๋ช…

You are given the root of a binary search tree (BST) and an integer val.
Find the node in the BST that the node's value equals val and return the subtree rooted with that node.
If such a node does not exist, return null.

๊ฒฐ๊ณผ ์˜ˆ์‹œ

root์˜ ํƒ€์ž…๊ณผ ๋ฐ˜ํ™˜ํƒ€์ž…์€ TreeNode์ž…๋‹ˆ๋‹ค. ๋ฆฌ์ŠคํŠธํ˜•์‹ ์•„๋‹™๋‹ˆ๋‹ค.

Example 1

Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]

Example 2

Input: root = [4,2,7,1,3], val = 5
Output: []

์ œํ•œ์‚ฌํ•ญ

  • The number of nodes in the tree is in the range [1, 5000].
  • 1<=1 <= Node.val <=107<= 10^7
  • root is a binary search tree.
  • 1<=1 <= val <=107<= 10^7


๐ŸงŠ ํŒŒ์ด์ฌ ์ฝ”๋“œ

class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if not root : return None
        if val == root.val : return root #๋ฃจํŠธ๊ฐ€ ๊ฐ’์ด ๊ฐ™์œผ๋ฉด ๊ทธ ํŠธ๋ฆฌ ๋ฐ˜ํ™˜
        tree = self.searchBST(root.left, val)
        return self.searchBST(root.right, val) if tree == None else tree

์ €๋Š” DFS๋กœ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค.

๐Ÿน ๋‹ค๋ฅธ์‚ฌ๋žŒ ์ฝ”๋“œ

class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if root is None or root.val == val: 
            return root # Return that node.
        return self.searchBST(root.left,val) if root.val > val else self.searchBST(root.right,val) 

๋กœ์ง์€ ๋น„์Šทํ•ด๋ณด์ด์ง€๋งŒ ๋” ์ฝ”๋“œ๊ฐ€ ๋” ๊ฐ„๊ฒฐํ•ฉ๋‹ˆ๋‹ค.

๐Ÿธ ๋˜๋‹ค๋ฅธ์‚ฌ๋žŒ ์ฝ”๋“œ

class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        while root:
            if root.val==val:
                return root
            if root.val>val:
                root=root.left
            else:
                root=root.right
        return None

์ด๊ฑด ์žฌ๊ท€๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค.
๊ทผ๋ฐ ์†๋„๋Š” ๋น„์Šทํ•˜๊ฒŒ ์ธก์ •๋˜๋„ค์š”.

0๊ฐœ์˜ ๋Œ“๊ธ€