二叉搜索树,删除节点

方法如下:
如果x没有子节点,或者只有一个孩子,直接将x切下
如果x有两个孩子,我们有其右子树中的最小值替换x,然后将左子树中的这一最小值切掉

  1. /**
  2. * 删除节点
  3. * */
  4. public BSTreeNode<T> Delete(BSTreeNode<T> t ,BSTreeNode<T> x) {
  5. if (x == null) return Root;
  6. BSTreeNode<T> root = t;
  7. BSTreeNode<T> oldX= x;
  8. BSTreeNode<T> parent = x.parent;
  9. if (x.left == null) {
  10. x = x.right;
  11. } else if (x.right == null) {
  12. x = x.left;
  13. } else {
  14. BSTreeNode<T> y = Min(x.right);
  15. x.key = y.key;
  16. if (y.parent != x) {
  17. y.parent.left = y.right;
  18. } else {
  19. x.right = y.right;
  20. }
  21. return root;
  22. }
  23. if (x != null) {
  24. x.parent = parent;
  25. }

  26. if (parent == null) {
  27. root = x;
  28. } else {
  29. if (parent.left == oldX) {
  30. parent.left = x;
  31. } else {
  32. parent.right = x;
  33. }
  34. }
  35. return Root;
  36. }





原文地址:https://www.cnblogs.com/xiejunzhao/p/82342e47bc71a6636cb40f302a0dbc76.html