zoukankan      html  css  js  c++  java
  • Java数据结构——二叉树节点的增删改查、获取深度及最大最小值

    一、查找最大值

    // 查找最大值
    public static Node maxNode() {
    Node node = root;
    Node maxNode = node;
    while (node != null) {
    maxNode = node;
    node = node.getRichild();
    }
    return maxNode;
    }
    

      

    二、查找最小值

    // 查找最小值
    public static Node minNode() {
    Node node = root;
    Node minNode = node;
    while (node != null) {
    minNode = node;
    node = node.getLechild();
    }
    return minNode;
    }
    

      

    三、插入节点

    // 插入节点
    public static boolean insert(Object data, Node parent) {
    Node node = new Node(data, null, null);
    if (root == null || parent == null) {
    root = node;
    return true;
    } else if (parent.getLechild() != null && parent.getRichild() != null) {
    return false;
    } else {
    if (parent.getLechild() != null) {
    parent.setRichild(node);
    } else {
    parent.setLechild(node);
    }
    return true;
    }
    }
    

      

    四、查找节点

    // 查找节点
    public static Node find(Node n, Object data) {
    if (n != null) {
    if (n.getData() == data) {
    return n;
    } else {
    Node res = null;
    res = find(n.getLechild(), data);
    if (res == null) {
    res = find(n.getRichild(), data);
    }
    return res;
    }
    } else {
    return null;
    }
    }
    

      

    五、修改节点
    直接调用setData方法即可。


    六、删除子节点

    // 删除子节点
    public static void delete( Node node) {
    node.setRichild(null);
    node.setLechild(null);
    }
    

      

    七、求深度

    // 求深度
    //求最长路径
    public static int getDepth1(Node node) {
    if (node == null) {
    return 0;
    }
    if (node.getLechild() == null && node.getRichild() == null) {
    return 1;
    }
    if (node.getLechild() == null) {
    return getDepth1(node.getRichild()) + 1;
    }
    if (node.getRichild() == null) {
    return getDepth1(node.getLechild()) + 1;
    } else {
    return Math.max(getDepth1(node.getLechild()), getDepth1(node.getRichild())) + 1;
    }
    }
    
    // 求最小路径
    public static int getDepth2(Node node) {
    if (node == null) {
    return 0;
    }
    if (node.getLechild() == null && node.getRichild() == null) {
    return 1;
    }
    if (node.getLechild() == null) {
    return getDepth2(node.getRichild()) + 1;
    }
    if (node.getRichild() == null) {
    return getDepth2(node.getLechild()) + 1;
    } else {
    return Math.min(getDepth2(node.getLechild()), getDepth2(node.getRichild())) + 1;
    }
    }
  • 相关阅读:
    MFC编程入门之二十八(常用控件:列表视图控件List Control上)
    Discuz X1.5 利用添加好友处存储xss进行蠕虫worm扩散
    全民wifi钓鱼来临----agnes安卓wifi钓鱼神器介绍
    自改xss小平台上线
    谈网页游戏外挂之用python模拟游戏(热血三国2)登陆
    thinkpad t440p 解决无线网卡驱动
    编写php拓展实例--slime项目(用户登录会话类)
    用Tupper自我指涉公式造图
    一首歌
    rtx信息泄漏利结合弱口令导致被批量社工思路
  • 原文地址:https://www.cnblogs.com/ericz2j/p/10686528.html
Copyright © 2011-2022 走看看