在Java中,可以使用队列来实现按级别顺序(从左到右)插入节点的方法。具体步骤如下:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
Queue<TreeNode> queue = new LinkedList<>();
if (root == null) {
root = new TreeNode(val);
return root;
}
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode parent = queue.poll();
// 尝试插入左子节点
if (parent.left == null) {
parent.left = new TreeNode(val);
return root;
} else {
queue.offer(parent.left);
}
// 尝试插入右子节点
if (parent.right == null) {
parent.right = new TreeNode(val);
return root;
} else {
queue.offer(parent.right);
}
}
完整的代码如下:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public class BinaryTreeInsertion {
public static TreeNode insertLevelOrder(TreeNode root, int val) {
Queue<TreeNode> queue = new LinkedList<>();
if (root == null) {
root = new TreeNode(val);
return root;
}
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode parent = queue.poll();
// 尝试插入左子节点
if (parent.left == null) {
parent.left = new TreeNode(val);
return root;
} else {
queue.offer(parent.left);
}
// 尝试插入右子节点
if (parent.right == null) {
parent.right = new TreeNode(val);
return root;
} else {
queue.offer(parent.right);
}
}
return root;
}
public static void main(String[] args) {
TreeNode root = null;
root = insertLevelOrder(root, 1);
root = insertLevelOrder(root, 2);
root = insertLevelOrder(root, 3);
root = insertLevelOrder(root, 4);
root = insertLevelOrder(root, 5);
}
}
这个方法可以确保按级别顺序(从左到右)插入节点,即先从根节点开始,逐层遍历二叉树,找到第一个空闲位置插入新节点。
领取专属 10元无门槛券
手把手带您无忧上云