701. 二叉搜索树中的插入操作

96 阅读1分钟

题目:
给定二叉搜索树(BST)的根节点 root 和要插入树中的值 value ,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。

注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/in… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法:
主要考察bst的性质,左节点全部小于root节点,右节点大于root节点

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func insertIntoBST(root *TreeNode, val int) *TreeNode {
    // 斜数
    if root == nil {
        return &TreeNode{
            Val:val,
        }
    }
    insert(root, val)
    return root
}


func insert(root *TreeNode, val int) {
    if val < root.Val {
        if root.Left != nil {
            insert(root.Left, val)
        } else {
            root.Left = &TreeNode{
                Val:val,
            } 
            
        }
        
    }
    if root.Val < val {
        if root.Right != nil {
            insert(root.Right, val)
        } else {
            root.Right = &TreeNode{
                Val:val,
            } 
            
        }
    }
}