235. 二叉搜索树的最近公共祖先
利用二叉搜索树的特性进行分析,先与根节点比较后盘点去左边还是右边。
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil {return nil}
maxval := int(math.Max(float64(p.Val), float64(q.Val)))
minval := int(math.Min(float64(p.Val), float64(q.Val)))
if maxval >= root.Val && minval <= root.Val {
return root
}
var leftptr, rightptr *TreeNode
if maxval < root.Val{
leftptr = lowestCommonAncestor(root.Left, p, q)
}
if minval > root.Val{
rightptr = lowestCommonAncestor(root.Right, p ,q)
}
if leftptr != nil{
return leftptr
}
if rightptr != nil{
return rightptr
}
return nil
}
701.二叉搜索树中的插入操作
可以插入到头节点,然后调整树,也可以插入到叶子节点。
插入头节点就是插入成功后可以直接返回头节点的地址,但是插入叶子节点的时候必须保留一下当前头节点的地址,要不然没有返回值。
func insertIntoBST(root *TreeNode, val int) *TreeNode {
tmp := &TreeNode{Val : val}
if root == nil{
return tmp
}
Bottominsert(root, tmp, val)
return root
}
func Bottominsert(node *TreeNode, ins *TreeNode, val int) {
if node.Val > val{
if node.Left == nil{
node.Left = ins
}else{
Bottominsert(node.Left, ins, val)
}
}else{
if node.Right == nil{
node.Right = ins
}else{
Bottominsert(node.Right, ins, val)
}
}
}
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 {
return root.Left
}
if root.Left == nil{
return root.Right
}
minnode := root.Right
for minnode.Left != nil {
minnode = minnode.Left
}
minnode.Left = root.Left
root = root.Right
//root.Val = minnode.Val
//root.Right = deleteNode1(root.Right)
return root
}