二叉树insert方法仅能插入根节点,其余节点无法插入的问题排查
二叉树insert方法插入失败原因分析
核心问题
你的insert方法仅能插入根节点,其余节点无法添加的根本原因是:遍历找到空位置后,只是修改了局部变量current的指向,没有更新父节点的leftChild或rightChild引用,导致新节点从未真正挂载到二叉树上。
具体过程分析
- 插入非根节点时,你通过
current从根节点开始遍历,每次根据值的大小移动到左/右子节点,直到current变为null。 - 此时
current只是一个指向null的局部变量,你执行current = node只会改变这个局部变量的指向,完全不会影响之前父节点的子节点引用(父节点的leftChild或rightChild仍然是null)。
修正后的代码
public class Tree { private class Node { int value; Node leftChild; Node rightChild; public Node(int value) { this.value = value; } @Override public String toString() { return "Node=" + value; } } private Node root; public void insert(int value) { var node = new Node(value); if(root == null) { root = node; return; } var current = root; while (true) { if(value > current.value) { // 右子节点为空时,直接挂载新节点并退出循环 if(current.rightChild == null) { current.rightChild = node; break; } current = current.rightChild; } else { // 左子节点为空时,直接挂载新节点并退出循环 if(current.leftChild == null) { current.leftChild = node; break; } current = current.leftChild; } } } }
修正说明
- 调整遍历逻辑:不再等到
current变为null,而是在遍历过程中检查当前节点的子节点是否为空。 - 直接挂载新节点:当找到合适的空位置(父节点的左/右子节点为空),立即将父节点的对应子节点引用指向新节点,确保新节点被添加到树结构中。
内容的提问来源于stack exchange,提问作者DMN
相关产品推荐
相关产品推荐

