알고리즘/해결

LeetCode700. Search in a Binary Search Tree

언클린 2020. 3. 23. 21:07
728x90

1. 문제(원본)

Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.

In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL.

Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null.

2. 문제

해당 트리를 탐색하라

public class TreeNode {

    public var val: Int

    public var left: TreeNode?

    public var right: TreeNode?

    public init(_ val: Int) {

        self.val = val

        self.left = nil

        self.right = nil

    }

}

3. 나의 답

class Solution {

    func searchBST(_ root: TreeNode?, _ val: Int) -> TreeNode? {

        guard (root != nil) else {

            return nil

        }

 

        if root?.val == val {

            return root

        }

 

        let left = self.searchBST(root?.left, val)

        if left?.val == val {

            return left

        }

        let right = self.searchBST(root?.right, val)

        if right?.val == val {

            return right

        }

 

        return nil

    }

}

4. 다른 유저의 답

#1

class Solution {

    func searchBST(_ root: TreeNode?, _ val: Int) -> TreeNode? {

        

        guard let node = root else { return nil }

        

        if node.val == val { return root }

        if node.val > val  { return searchBST(node.left, val) }

        if node.val < val  { return searchBST(node.right, val) }

        

        return nil

    }

}

5. 마무리

저번에 트리 문제를 하나 풀고나서 이번 문제도 수월하게 풀 수 있었다. 하나를 오랫동안 고민해서 해결하고 나니 그 다음 부터는 응용을 쉽게 하게 되어 문제 해결법을 금방 찾을 수 있게 되는 것 같다.

 

728x90