LeetCode之Search in a Binary Search Tree(Kotlin)

404 阅读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.

For example, 
Given the tree:
        4
       / \
      2   7
     / \
    1   3

And the value to search: 2

方法: 递归调用检索,唯一不同于普通树的是二叉搜索树可以减少递归调用次数,看下二叉搜索树的定义就懂了。

具体实现:

class SearchInABinarySearchTree {

    class TreeNode(var `val`: Int = 0) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }

    fun searchBST(root: TreeNode?, `val`: Int): TreeNode? {
        if (root == null) {
            return null
        }
        if(root.`val` == `val`) {
            return root
        } else if (root.`val` > `val`) {
            return searchBST(root.left, `val`)
        } else {
            return searchBST(root.right, `val`)
        }
    }
}

fun main(args: Array<String>) {

}

有问题随时沟通

具体代码实现可以参考Github