|
@@ -1,5 +1,5 @@
|
|
|
/**
|
|
|
- * Definition for a binary tree node.
|
|
|
+ * Definition for a binary tree root.
|
|
|
* type TreeNode struct {
|
|
|
* Val int
|
|
|
* Left *TreeNode
|
|
@@ -7,5 +7,31 @@
|
|
|
* }
|
|
|
*/
|
|
|
func deleteNode(root *TreeNode, key int) *TreeNode {
|
|
|
-
|
|
|
+ if root == nil {
|
|
|
+ return nil
|
|
|
+ }
|
|
|
+ if root.Val == key {
|
|
|
+ if root.Left == nil && root.Right == nil {
|
|
|
+ return nil
|
|
|
+ } else if root.Left == nil {
|
|
|
+ return root.Right
|
|
|
+ } else if root.Right == nil {
|
|
|
+ return root.Left
|
|
|
+ } else {
|
|
|
+ min := findMin(root.Right)
|
|
|
+ root.Val, min.Val = min.Val, root.Val
|
|
|
+ root.Right = deleteNode(root.Right, key)
|
|
|
+ }
|
|
|
+ } else if key < root.Val {
|
|
|
+ root.Left = deleteNode(root.Left, key)
|
|
|
+ } else {
|
|
|
+ root.Right = deleteNode(root.Right, key)
|
|
|
+ }
|
|
|
+ return root
|
|
|
+}
|
|
|
+
|
|
|
+func findMin(root *TreeNode) (min *TreeNode) {
|
|
|
+ for min = root; min.Left != nil; min = min.Left {
|
|
|
+ }
|
|
|
+ return
|
|
|
}
|