zoukankan      html  css  js  c++  java
  • 二叉树的节点删除

      二叉树的节点删除

         二叉树节点的删除,大家马上脑海里就马上想到的是一颗二叉树,然后我们要删除它的叶子节点,删除的非叶子节点,应该怎么做呢,想到的时候,好像感觉很复杂的样子。其实我们只要慢慢分析,总是能把他搞出来的。

         首先请看我们的分析过程,大概如下图所示:

        

        这里的大概误区就是:我们一般删除,想到的方法就是直接和跟结点进行比较了,然后就开始写代码了。其实我们只要仔细分析一下,就会得出上面的结论。

        接下来根据上面的分析,得出具体的思路:

        

        代码如下:

        public static Boolean deleteByNo(HeroNode node,int no){
            if(node.getLeft()!=null){
                if(node.getLeft().getNo()==no){
                    node.setLeft(null);
                    return true;
                }
            }
            if(node.getRight()!=null){
                if(node.getRight().getNo()==no){
                    node.setRight(null);
                    return  true;
                }
            }
            if(node.getNo()==no){
                node=null;
                return true;
            }
            Boolean flag=false;
            if(node.getLeft()!=null){
                flag=deleteByNo(node.getLeft(),no);
            }
            if(flag){
                return  flag;
            }
            if(node.getRight()!=null){
                flag=deleteByNo(node.getRight(),no);
            }
            return  flag;
        }

        测试代码如下:

        HeroNode node1=new HeroNode(1,"及时雨","宋江");
            HeroNode node2=new HeroNode(2,"玉麒麟","卢俊义");
            HeroNode node3=new HeroNode(3,"智多星","吴用");
            HeroNode node4=new HeroNode(4,"花和尚","鲁智深");
            HeroNode node5=new HeroNode(5,"豹子头","林冲");
            HeroNode node6=new HeroNode(6,"矮脚虎","王英");
    
            node1.setLeft(node2);
            node1.setRight(node3);
            node2.setLeft(node4);
            node2.setRight(node5);
            node3.setRight(node6);
    
            //现在要删除节点3。怎么删除呢。
             Boolean flag=deleteByNo(node1,3);
             if(flag){
                 System.out.println("删除成功");
             }else{
                 System.out.println("删除失败");
             }

        

    终极目标:世界大同
  • 相关阅读:
    mysql 无法连接提示 Authentication plugin 'caching_sha2_password' cannot be loaded
    探究分析:快速对大量的数据转换为数组
    SQL Server like 字段
    InfluxDB从原理到实战
    Python学习日记(四十) Mysql数据库篇 八
    MySQL数据库基本操作
    ES入门宝典(详细截图版)
    NameNode && Secondary NameNode工作机制
    MySQL 两张表关联更新(用一个表的数据更新另一个表的数据)
    mysql单个表拆分成多个表
  • 原文地址:https://www.cnblogs.com/gdouzz/p/14308702.html
Copyright © 2011-2022 走看看