dengxinyi 6 年之前
父節點
當前提交
1671607256
共有 1 個文件被更改,包括 28 次插入2 次删除
  1. 28 2
      medium/450.delete-node-in-a-bst.go

+ 28 - 2
medium/450.delete-node-in-a-bst.go

@@ -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
 }