LeetCode之Insert into a Binary Search Tree(Kotlin)

問(wèn)題:
Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

For example, 

Given the tree:
        4
       / \
      2   7
     / \
    1   3
And the value to insert: 5
You can return this binary search tree:

         4
       /   \
      2     7
     / \   /
    1   3 5
This tree is also valid:

         5
       /   \
      2     7
     / \   
    1   3
         \
          4

方法:
二叉搜索樹(shù)的遞歸,重點(diǎn)在于理順遞歸調(diào)用邏輯,具體實(shí)現(xiàn)參考代碼。

具體實(shí)現(xiàn):

class InsertIntoABinarySearchTree {

    // Definition for a binary tree node.
    class TreeNode(var `val`: Int = 0) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }

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

fun main(args: Array<String>) {

}

有問(wèn)題隨時(shí)溝通

具體代碼實(shí)現(xiàn)可以參考Github

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,817評(píng)論 0 10
  • “鞋子合不合腳,只有腳知道”,這個(gè)道理原本我們都明白,只是,我們還是喜歡對(duì)別人評(píng)頭論足,大概只有這樣才讓生活顯的有...
    不倒翁Miss閱讀 465評(píng)論 0 1
  • 你累了 懷揣鄉(xiāng)愁走了九十余年 你魂?duì)繅?mèng)縈的故鄉(xiāng)在哪里 你魂?duì)繅?mèng)縈的故國(guó)又在哪里 歷經(jīng)兩百余年的恥辱 故國(guó)在搖搖晃晃...
    胡鑠閱讀 283評(píng)論 0 1
  • 整流二極管 整流:將交流電轉(zhuǎn)變?yōu)橹绷麟姟?半波整流:使用變壓器將市電 AC~ 220sinwt(V) 降低下來(lái)轉(zhuǎn)為...
    海青CAUC閱讀 2,311評(píng)論 0 49
  • 控制好你的自制力,選對(duì)習(xí)慣,你無(wú)須向外索取,卓越的成就自會(huì)找上門(mén)來(lái)。 追求極致必定會(huì)帶來(lái)真刀真槍的挑戰(zhàn),成功總在平...
    零度清爽閱讀 151評(píng)論 0 0

友情鏈接更多精彩內(nèi)容