// 定义二叉树节点类
class TreeNode {
int val; // 节点的值
TreeNode left; // 左子节点
TreeNode right; // 右子节点
// 构造函数
TreeNode(int x) {
val = x;
left = null;
right = null;
}
}
// 定义二叉树类
class BinaryTree {
TreeNode root; // 树的根节点
// 构造函数
BinaryTree() {
root = null;
}
// 插入节点的方法(递归实现)
public void insert(int value) {
root = insertRec(root, value);
}
// 递归插入节点
private TreeNode insertRec(TreeNode root, int value) {
if (root == null) {
root = new TreeNode(value);
return root;
}
if (value < root.val) {
root.left = insertRec(root.left, value);
} else if (value > root.val) {
root.right = insertRec(root.right, value);
}
return root;
}
// 中序遍历方法(递归实现)
public void inorderTraversal() {
inorderRec(root);
}
// 递归中序遍历
private void inorderRec(TreeNode root) {
if (root != null) {
inorderRec(root.left);
System.out.print(root.val + " ");
inorderRec(root.right);
}
}
}
// 测试代码
public class Main {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
// 打印中序遍历结果
System.out.println("Inorder traversal of the constructed tree is:");
tree.inorderTraversal();
}
}
val,以及指向左子节点和右子节点的引用 left 和 right。insert 方法用于将新节点插入到正确的位置,inorderTraversal 方法用于按中序遍历顺序打印树中的节点。这个例子展示了如何构建和操作一个简单的二叉搜索树(BST)。
上一篇:java 两个集合取交集
下一篇:java获取yml文件配置
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站