• 二叉搜索树删除元素likou450


    本题我自己做只得了80%左右,主要是删除根节点时没处理好。

    这一题我吸取的上一题的教训,用了二叉搜索树的特性:

    左节点小于根节点

    右节点大于根节点

    所以我们的递归还是得使用三个主判断:

    小于、大于、等于指定元素时怎么做:

    根节点值小于指定元素时,就说明在需要删除的元素在右边、向右递归

    根节点值大于指定元素时,就在左边、向左递归。

    等于时,就要进行删除操作:

            分为三个条件:

            1、待删除节点左、右节点都是空时,就说明是叶子节点,后面什么都没了,直接返回null。

            2、左节点为空或者右节点为空,就说明需要返回非空节点下面的子树,将非空的节点子树返回就好了。

            3、左、右节点都不为空时,这个时候就比较麻烦了:删除节点后,要保持二叉搜索树的特性,所以就得怎么做:

            将待删除节点的左节点全部加入到待删除节点右子树的左子叶上、

            因为删除节点的右节点一定比左节点大,而且它也是二叉搜索树,它的左节点一定是整颗二叉树合理的地方。

     

    1. package shuJuJieGouYuSuanFa.erChaShu;
    2. public class likou450 {
    3. public static void main(String[] args) {
    4. TreeNode root = TreeNode.getBST();
    5. int key = 8;
    6. TreeNode ans = new likou450().deleteNode(root, key);
    7. peint(ans);
    8. }
    9. //打印输出二叉树,前序遍历
    10. private static void peint(TreeNode ans) {
    11. if (ans == null) {
    12. return;
    13. }
    14. System.out.print(ans.val + " ");
    15. peint(ans.left);
    16. peint(ans.right);
    17. }
    18. public TreeNode deleteNode(TreeNode root, int key) {
    19. return dfs(root, key);
    20. }
    21. private TreeNode dfs(TreeNode root, int key) {
    22. if (root == null) {
    23. return null;
    24. }
    25. if (root.val < key) {
    26. root.right = dfs(root.right, key);
    27. } else if (root.val > key) {
    28. root.left = dfs(root.left, key);
    29. } else {
    30. if (root.left == null && root.right == null) {
    31. return null;
    32. } else if (root.left == null) {
    33. return root.right;
    34. } else if (root.right == null) {
    35. return root.left;
    36. } else if (root.left != null && root.right != null) {
    37. TreeNode t = root.right;
    38. while (t.left != null) {
    39. t = t.left;
    40. }
    41. t.left = root.left;
    42. root = root.right;
    43. return root;
    44. }
    45. }
    46. return root;
    47. }
    48. }

     难度还是有点的,自己带得努力,暗自加油吧!

  • 相关阅读:
    7.26模拟赛总结
    AttributeError: ‘NoneType‘ object has no attribute ‘get_fetch_list‘
    自动化视频质量保障
    域名的理解
    今日多写一行注释,明日维护少掉一根头发
    原子操作类
    22. 概率与统计 - 贝叶斯统计&机器学习分类指标
    quarkus依赖注入之六:发布和消费事件
    ubuntu安装mysql详细过程
    常用压缩解压缩命令
  • 原文地址:https://blog.csdn.net/qx020814/article/details/127737839