java计算二叉树的节点最小值_Java数据结构——二叉树节点的增删改查、获取深度及最大最小值...

这篇博客详细介绍了如何使用Java实现二叉树中节点的常见操作,包括查找最大值和最小值、插入新节点、查找指定节点、修改节点数据、删除子节点以及计算树的深度。通过提供的方法,可以方便地进行二叉树的各种操作。
摘要由CSDN通过智能技术生成

一、查找最大值

// 查找最大值

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值