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;
}
}

 

转载于:https://www.cnblogs.com/ericz2j/p/10686528.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值