代码随想录算法训练营第十九天 | 235、701、450

235. 二叉搜索树的最近公共祖先

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main

/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/

func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
// 确定 p 和 q 的值中的最小值和最大值
pVal, qVal := p.Val, q.Val
if pVal > qVal {
pVal, qVal = qVal, pVal
}

current := root
for current != nil {
// 当前节点值比最大值大,LCA 在左子树
if current.Val > qVal {
current = current.Left
// 当前节点值比最小值小,LCA 在右子树
} else if current.Val < pVal {
current = current.Right
// 当前节点介于 p 和 q 之间(或等于其中一个),即为 LCA
} else {
return current
}
}
return nil // 题目保证存在,此处不会执行
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

/**
* 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}
}
if val < root.Val {
root.Left = insertIntoBST(root.Left, val)
} else {
root.Right = insertIntoBST(root.Right, val)
}
return root
}

450. 删除二叉搜索树中的节点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main

/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func deleteNode(root *TreeNode, key int) *TreeNode {
if root == nil {
return nil
}
if key < root.Val {
root.Left = deleteNode(root.Left, key)
} else if key > root.Val {
root.Right = deleteNode(root.Right, key)
} else {
// 当前节点为要删除的节点
if root.Left == nil {
return root.Right
} else if root.Right == nil {
return root.Left
} else {
// 找到右子树的最小节点
minNode := findMin(root.Right)
root.Val = minNode.Val
// 删除右子树中的最小节点
root.Right = deleteNode(root.Right, minNode.Val)
}
}
return root
}

// 辅助函数:找到子树的最小节点
func findMin(node *TreeNode) *TreeNode {
for node.Left != nil {
node = node.Left
}
return node
}