235. 二叉搜索树的最近公共祖先
代码如下
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil {
return nil
}
for {
if root.Val > p.Val && root.Val > q.Val { 如果pq节点都在该节点小,则pq节点一定在这个节点的左子树
root = root.Left
}
if root.Val < p.Val && root.Val < q.Val { 同理如果pq节点都比该节点大,则pq节点一定在该节点的右子树
root = root.Right
}
if (root.Val - p.Val) * (root.Val - q.Val) <= 0 { 如果当前节点大于p小于q或者相反,那么说明该节点是pq的最近公共祖先
return root
}
}
}
701. 二叉搜索树中的插入操作
代码如下
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
}
450. 删除二叉搜索树中的节点
代码如下
func deleteNode(root *TreeNode, key int) *TreeNode {
if root == nil {
return nil
}
if key < root.Val { 首先寻找要删除的节点,如果这个节点的大小小于当前节点,则往左子树上寻找
root.Left = deleteNode(root.Left,key)
return root
}
if key > root.Val {
root.Right = deleteNode(root.Right,key) 如果大于当前节点,则往右子树上寻找
return root
}
if root.Right == nil && root.Left == nil { 此时说明该节点已经是要删除的节点,如果这个节点是叶子节点,则直接向上层返回nil,就删除该节点
return nil
}
if root.Right == nil { 如果这个节点的右子树为空,则返回左子树
return root.Left
}
if root.Left == nil { 同理,左子树为空,返回右子树
return root.Right
}
minnode := root.Right 如果左右子树都不为空,则记录下右子树
for minnode.Left != nil { 在右子树的左子树,找到最小节点,即一直往左子树上递归直到为空
minnode = minnode.Left
}
root.Val = minnode.Val 将这个值赋值给要删除的节点
root.Right = deletenode1(root.Right) 此时再去删除右子树的最小节点
return root
}
func deletenode1(root * TreeNode) *TreeNode {
if root.Left == nil { 如果该节点的左子树为空,则说明该节点就是整个树的最小节点,说明需要删除这个节点
pright := root.Right
root.Right = nil
return pright
}
root.Left = deletenode1(root.Left) 如果左子树不为空,则一直向左子树递归
return root
}