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

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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

相关文档
最新文档