450.delete-node-in-a-bst.go 791 B

12345678910111213141516171819202122232425262728293031323334353637
  1. /**
  2. * Definition for a binary tree root.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func deleteNode(root *TreeNode, key int) *TreeNode {
  10. if root == nil {
  11. return nil
  12. }
  13. if root.Val == key {
  14. if root.Left == nil && root.Right == nil {
  15. return nil
  16. } else if root.Left == nil {
  17. return root.Right
  18. } else if root.Right == nil {
  19. return root.Left
  20. } else {
  21. min := findMin(root.Right)
  22. root.Val, min.Val = min.Val, root.Val
  23. root.Right = deleteNode(root.Right, key)
  24. }
  25. } else if key < root.Val {
  26. root.Left = deleteNode(root.Left, key)
  27. } else {
  28. root.Right = deleteNode(root.Right, key)
  29. }
  30. return root
  31. }
  32. func findMin(root *TreeNode) (min *TreeNode) {
  33. for min = root; min.Left != nil; min = min.Left {
  34. }
  35. return
  36. }