第二十二天算法设计
BinaryTree 类:
java
package suanfa;
public class BinaryTree {
// 定义树的节点类
private static class Node {
int value;
Node left, right;
public Node(int value) {
this.value = value;
left = right = null;
}
}
private Node root;
// 构造函数,初始化空树
public BinaryTree() {
root = null;
}
// 插入节点到二叉树
public void insert(int value) {
root = insertRec(root, value);
}
// 递归的插入节点
private Node insertRec(Node root, int value) {
// 如果树为空,返回新节点
if (root == null) {
root = new Node(value);
return root;
}
// 否则,递归地插入到左子树或右子树
if (value < root.value) {
root.left = insertRec(root.left, value);
} else if (value > root.value) {
root.right = insertRec(root.right, value);
}
// 返回未改变的节点指针
return root;
}
// 中序遍历:左 -> 根 -> 右
public void inOrder() {
inOrderRec(root);
}
// 递归的中序遍历
private void inOrderRec(Node root) {
if (root != null) {
inOrderRec(root.left); // 遍历左子树
System.out.print(root.value + " "); // 访问根节点
inOrderRec(root.right); // 遍历右子树
}
}
}
BinaryTreeTest 类:
java
package suanfa;
public class BinaryTreeTest {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
// 插入节点
tree.insert(4);
tree.insert(5);
tree.insert(6);
tree.insert(3);
tree.insert(2);
tree.insert(1);
// 中序遍历 (左 -> 根 -> 右)
System.out.print("中序遍历: ");
tree.inOrder(); // 输出结果:1 2 3 4 5 6
}
}
录制: untitled2 – Insertion.java
录制文件:https://meeting.tencent.com/crm/KzGGkGE85d
浙公网安备 33010602011771号