본문 바로가기

Algorithms and Data Structures/Leetcode

Leetcode 700. Search in a Binary Search Tree

자바 재귀

class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if (root == null || val == root.val)
            return root;
        
        return val < root.val ? searchBST(root.left, val) : searchBST(root.right, val);
    }
}

 

파이썬 이터레이션

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