代码:用java实现二叉树,给节点填充字符元素
时间: 2024-05-12 22:15:52 浏览: 8
好的,我可以回答这个问题。以下是一份用Java实现二叉树并填充字符元素的代码示例:
```java
class Node {
char data;
Node left, right;
public Node(char item) {
data = item;
left = right = null;
}
}
class BinaryTree {
Node root;
public BinaryTree() {
root = null;
}
void insert(char key) {
root = insertRec(root, key);
}
Node insertRec(Node root, char key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.data)
root.left = insertRec(root.left, key);
else if (key > root.data)
root.right = insertRec(root.right, key);
return root;
}
void inorder() {
inorderRec(root);
}
void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.print(root.data + " ");
inorderRec(root.right);
}
}
}
public class Main {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.insert('A');
tree.insert('B');
tree.insert('C');
tree.insert('D');
tree.insert('E');
tree.insert('F');
tree.insert('G');
tree.inorder();
}
}
```
输出结果是:`A B C D E F G`,表示节点的字符元素是按照中序遍历顺序进行填充的。