数据结构与算法--二叉搜索树节点删除

素颜马尾好姑娘i 2022-09-04 15:54 300阅读 0赞

二叉搜索树的节点删除代码

  1. class Solution {
  2. public TreeNode deleteNode(TreeNode root, int key) {
  3. if (root == null) {
  4. return null;
  5. }
  6. if (key < root.val) {
  7. // 待删除节点在左子树中
  8. root.left = deleteNode(root.left, key);
  9. return root;
  10. } else if (key > root.val) {
  11. // 待删除节点在右子树中
  12. root.right = deleteNode(root.right, key);
  13. return root;
  14. } else {
  15. // key == root.val,root 为待删除节点
  16. if (root.left == null) {
  17. // 返回右子树作为新的根
  18. return root.right;
  19. } else if (root.right == null) {
  20. // 返回左子树作为新的根
  21. return root.left;
  22. } else {
  23. // 左右子树都存在,返回后继节点(右子树最左叶子)作为新的根
  24. TreeNode successor = min(root.right);
  25. successor.right = deleteMin(root.right);
  26. successor.left = root.left;
  27. return successor;
  28. }
  29. }
  30. }
  31. private TreeNode min(TreeNode node) {
  32. if (node.left == null) {
  33. return node;
  34. }
  35. return min(node.left);
  36. }
  37. private TreeNode deleteMin(TreeNode node) {
  38. if (node.left == null) {
  39. return node.right;
  40. }
  41. node.left = deleteMin(node.left);
  42. return node;
  43. }
  44. }

发表评论

表情:
评论列表 (有 0 条评论,300人围观)

还没有评论,来说两句吧...

相关阅读

    相关 数据结构算法:搜索

    希望大家可以自己动手练习一下,算法光看是不行的,必须亲自动手敲代码,有时候你会发现自己有思路,但是又写不出来,这就是缺乏练习的原因。大家平时在做题的时候,可以多思考,多总...

    相关 数据结构————搜索

    二叉搜索树也叫二叉查找树,二叉排序树,BST。这是学习二叉平衡树、多路平衡树、B-树、B+树的基础。凡事要有个循序渐进。B+树在数据库中得到了应用,我想我们也非常有必要去了解它