LeetCode701. 二叉搜索树中的插入操作Golang版
LeetCode701. 二叉搜索树中的插入操作Golang版
1. 问题描述
给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。
2. 思路
2.1. 递归
- 确定递归函数参数和返回值
func insertIntoBST(root *TreeNode, val int) *TreeNode
- 确定终止条件
if root == nil {
node := &TreeNode{
Val : val,
Left : nil,
Right : nil,
}
return node
}
- 确定单层递归逻辑
if root.Val > val {
root.Left = insertIntoBST(root.Left, val)
}
if root.Val < val {
root.Right = insertIntoBST(root.Right, val)
}
return root
2.2. 迭代
利用二叉搜索树的有序性
3. 代码
3.1. 递归代码
/**
* 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 {
node := &TreeNode{
Val : val,
Left : nil,
Right : nil,
}
return node
}
if root.Val > val {
root.Left = insertIntoBST(root.Left, val)
}
if root.Val < val {
root.Right = insertIntoBST(root.Right, val)
}
// 但凡是return root的递归,下层向上层的数据传递,不会影响上层向更上层的传递
return root
}
3.2. 迭代代码
/**
* 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 {
node := &TreeNode {
Val : val,
Left : nil,
Right : nil,
}
return node
}
current := root
prev := root
for current != nil {
prev = current
if current.Val < val {
current = current.Right
} else {
current = current.Left
}
}
node := &TreeNode {
Val : val,
Left : nil,
Right : nil,
}
if val < prev.Val {
prev.Left = node
} else {
prev.Right = node
}
return root
}
