1. 程式人生 > >Java數據結構——二叉樹節點的增刪改查、獲取深度及最大最小值

Java數據結構——二叉樹節點的增刪改查、獲取深度及最大最小值

brush java數據結構 public bool 方法 ret 樹節點 增刪改查 bject

一、查找最大值

// 查找最大值
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;
}
}

Java數據結構——二叉樹節點的增刪改查、獲取深度及最大最小值