java二叉树
时间: 2023-08-30 18:05:48 浏览: 42
Java中的二叉树可以通过类和节点来实现。每个节点包含一个值和指向左右子节点的指针。以下是一个基本的二叉树实现:
```java
class Node {
int value;
Node left, right;
public Node(int value) {
this.value = value;
left = right = null;
}
}
class BinaryTree {
Node root;
public BinaryTree() {
root = null;
}
public void insert(int value) {
root = insertNode(root, value);
}
private Node insertNode(Node root, int value) {
if (root == null) {
root = new Node(value);
return root;
}
if (value < root.value) {
root.left = insertNode(root.left, value);
} else if (value > root.value) {
root.right = insertNode(root.right, value);
}
return root;
}
public void inorder() {
inorderTraversal(root);
}
private void inorderTraversal(Node root) {
if (root != null) {
inorderTraversal(root.left);
System.out.print(root.value + " ");
inorderTraversal(root.right);
}
}
}
public class Main {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.insert(4);
tree.insert(2);
tree.insert(5);
tree.insert(1);
tree.insert(3);
System.out.println("Inorder traversal of binary tree is: ");
tree.inorder();
}
}
```
以上代码创建了一个类`Node`表示二叉树的节点,包含值和左右子节点的指针。类`BinaryTree`包含一个根节点和插入和遍历二叉树的方法。`insert`方法用于插入值,`inorder`方法用于中序遍历二叉树。最后的`main`方法创建了一棵二叉树并输出了中序遍历结果。