生成一个Java的二叉树代码,带注解
时间: 2023-03-10 09:57:18 浏览: 59
public class BinaryTree {
//根节点
Node root;
//节点类
class Node {
int key;
Node left;
Node right;
//构造函数
public Node(int key) {
this.key = key;
left = null;
right = null;
}
}
//构造函数
public BinaryTree() {
root = null;
}
//根据给定的键插入一个节点
public void insert(int key) {
root = insertRec(root, key);
}
//递归函数来插入节点
public Node insertRec(Node root, int key) {
//如果根节点是空的,则创建一个新的节点并返回
if (root == null) {
root = new Node(key);
return root;
}
//如果节点的值小于根节点,则将其插入到左子树中
if (key < root.key)
root.left = insertRec(root.left, key);
//如果节点的值大于根节点,则将其插入到右子树中
else if (key > root.key)
root.right = insertRec(root.right, key);
return root;
}
}