LeetCode之Search in a Binary Search Tree(Kotlin)

問題: 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.node

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

And the value to search: 2
複製代碼

方法: 遞歸調用檢索,惟一不一樣於普通樹的是二叉搜索樹能夠減小遞歸調用次數,看下二叉搜索樹的定義就懂了。git

具體實現:github

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>) {

}
複製代碼

有問題隨時溝通bash

具體代碼實現能夠參考Githubui

相關文章
相關標籤/搜索