golang力扣leetcode 701. 二叉搜索树中的插入操作

简介: golang力扣leetcode 701. 二叉搜索树中的插入操作

题解

思路:找到最后一个叶子节点满足插入条件即可

代码

type TreeNode struct {
  Val   int
  Left  *TreeNode
  Right *TreeNode
}
func insertIntoBST(root *TreeNode, val int) *TreeNode {
  if root == nil {
    root = &TreeNode{Val: val}
    return root
  }
  if root.Val > val {
    root.Left = insertIntoBST(root.Left, val)
  } else {
    root.Right = insertIntoBST(root.Right, val)
  }
  return root
}

坑点

先看wa的代码

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

分析

为什么传进去一个nil,我函数里不是创建了新的节点了吗?不是指针传递吗?思考一下,其实指针传递传递的是指针里面存的地址,只是把“nil”传给了“形参指针”,让形参指针存nil而已,形参指针和局部指针不是同一个,他们执行的地址是同一个。那么形参指针指向的地址变化了,和局部指针又有什么关系呢,局部指针依旧指向nil


目录
相关文章
|
11天前
|
Go 索引
Golang深入浅出之-切片(Slices)入门:创建、操作与扩容机制
【4月更文挑战第20天】Go语言中的切片是动态数组,提供灵活的操作和自动扩容。本文介绍了切片的创建(通过`make()`、数组创建和切片字面量)、基本操作(索引访问、切片、赋值追加和遍历)以及扩容机制(首次和后续扩容策略)。此外,还强调了切片与底层数组的关系、切片越界问题、`append()`的使用以及理解切片的关键点,帮助提升Go编程效率和代码质量。
28 0
|
20天前
Leetcode1038. 从二叉搜索树到更大和树(每日一题)
Leetcode1038. 从二叉搜索树到更大和树(每日一题)
|
3月前
|
Java
LeetCode题解-二叉搜索树中第K小的元素-Java
LeetCode题解-二叉搜索树中第K小的元素-Java
13 0
|
4月前
|
Go 容器 SQL
【Golang Leetcode】总目录(Day1~100)
【Golang Leetcode】总目录(Day1~100)
475 1
【Golang Leetcode】总目录(Day1~100)
|
4月前
|
算法
代码随想录Day34 LeetCode T343整数拆分 T96 不同的二叉搜索树
代码随想录Day34 LeetCode T343整数拆分 T96 不同的二叉搜索树
30 0
|
4月前
|
机器学习/深度学习 算法 测试技术
【单调栈】LeetCode:2818操作使得分最大
【单调栈】LeetCode:2818操作使得分最大
|
4月前
|
算法 测试技术 C#
【贪心算法】【中位贪心】LeetCode:100123.执行操作使频率分数最大
【贪心算法】【中位贪心】LeetCode:100123.执行操作使频率分数最大
|
4月前
|
存储 算法 测试技术
【深度优先】LeetCode1932:合并多棵二叉搜索树
【深度优先】LeetCode1932:合并多棵二叉搜索树
|
4月前
leetcode-1441:用栈操作构建数组
leetcode-1441:用栈操作构建数组
21 0
|
4月前
leetcode-1382:将二叉搜索树变平衡
leetcode-1382:将二叉搜索树变平衡
19 0