题目:
题解:
func deleteNode(root *TreeNode, key int) *TreeNode {
var cur, curParent *TreeNode = root, nil
for cur != nil && cur.Val != key {
curParent = cur
if cur.Val > key {
cur = cur.Left
} else {
cur = cur.Right
}
}
if cur == nil {
return root
}
if cur.Left == nil && cur.Right == nil {
cur = nil
} else if cur.Right == nil {
cur = cur.Left
} else if cur.Left == nil {
cur = cur.Right
} else {
successor, successorParent := cur.Right, cur
for successor.Left != nil {
successorParent = successor
successor = successor.Left
}
if successorParent.Val == cur.Val {
successorParent.Right = successor.Right
} else {
successorParent.Left = successor.Right
}
successor.Right = cur.Right
successor.Left = cur.Left
cur = successor
}
if curParent == nil {
return cur
}
if curParent.Left != nil && curParent.Left.Val == key {
curParent.Left = cur
} else {
curParent.Right = cur
}
return root
}