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;
    }
    }
  • 相关阅读:
    成都磨子桥技工学校 / 数据结构 Challenge 4
    圆桌问题(网络流24题)
    试题库问题(网络流24题)
    [AHOI2005]航线规划
    [AMPPZ2014]The Prices
    方格取数(网络流24题)
    太空飞行计划问题(网络流24题)
    Linux 学习3
    Linux 学习2
    Linux 学习1
  • 原文地址:https://www.cnblogs.com/ericz2j/p/10686528.html
Copyright © 2011-2022 走看看