LeetCode之Insert into a Binary Search Tree(Kotlin)

问题:
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

方法:
二叉搜索树的递归,重点在于理顺递归调用逻辑,具体实现参考代码。

具体实现:

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

}

有问题随时沟通

具体代码实现可以参考Github

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,195评论 0 10
  • “鞋子合不合脚,只有脚知道”,这个道理原本我们都明白,只是,我们还是喜欢对别人评头论足,大概只有这样才让生活显的有...
    不倒翁Miss阅读 3,130评论 0 1
  • 你累了 怀揣乡愁走了九十余年 你魂牵梦萦的故乡在哪里 你魂牵梦萦的故国又在哪里 历经两百余年的耻辱 故国在摇摇晃晃...
    胡铄阅读 1,819评论 0 1
  • 整流二极管 整流:将交流电转变为直流电。 半波整流:使用变压器将市电 AC~ 220sinwt(V) 降低下来转为...
    海青简书号阅读 6,637评论 0 49
  • 控制好你的自制力,选对习惯,你无须向外索取,卓越的成就自会找上门来。 追求极致必定会带来真刀真枪的挑战,成功总在平...
    零度清爽阅读 1,225评论 0 0

友情链接更多精彩内容