/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/funcdeleteNode(root*TreeNode,keyint)*TreeNode{ifroot==nil{returnnil}ifroot.Val==key{ifroot.Right==nil{returnroot.Left}else{newRoot:=root.Rightparent:=rootfornewRoot.Left!=nil{parent=newRootnewRoot=newRoot.Left}newRoot.Left=root.LeftifnewRoot!=root.Right{// 注意不要忘记执行 parent.Left = newRoot.Right
parent.Left=newRoot.RightnewRoot.Right=root.Right}returnnewRoot}}elseifroot.Val>key{root.Left=deleteNode(root.Left,key)}else{root.Right=deleteNode(root.Right,key)}returnroot}