Java 二叉树插入问题…..insert()仅在根节点的子节点中放置新节点
当我使用Java 二叉树插入问题…..insert()仅在根节点的子节点中放置新节点,java,Java,当我使用insert()将新节点插入到二叉树中时,它只在子节点的位置插入新节点,即使根节点已经有左、右子节点。它不是访问子节点来创建更深层次的二叉树 对不起,英语不好 class Node { int key; String value; Node lc = null; Node rc = null; Node(int k,String v) { key = k; value = v; }
insert()
将新节点插入到二叉树中时,它只在子节点的位置插入新节点,即使根节点已经有左、右子节点。它不是访问子节点来创建更深层次的二叉树
对不起,英语不好
class Node
{
int key;
String value;
Node lc = null;
Node rc = null;
Node(int k,String v)
{
key = k;
value = v;
}
public String toString()
{
return value + "is" + key;
}
}
class BT
{
Node root;
public void insert(int k,String v)
{
Node newnode = new Node(k,v);
if(root == null)
{
System.out.println("root");
root = newnode;
return;
}
Node n = root;
while(n != null)
{
if(newnode.key <= n.key)
{
n = n.lc;
System.out.println("left");
if(n==null){n = newnode; break;}
}
else
{
n = n.rc;
System.out.println("right");
if(n==null){n = newnode; break;}
}
}
System.out.println("loop ended");
return;
}
}
public class test
{
public static void main(String arg[])
{
BT list = new BT();
list.insert(19,"one");
list.insert(67,"sixtyseven");
list.insert(5,"five");
list.insert(12,"twelve");
list.insert(67,"sixtyseven");
}
}
类节点
{
int键;
字符串值;
节点lc=null;
节点rc=null;
节点(整数k,字符串v)
{
key=k;
值=v;
}
公共字符串toString()
{
返回值+“是”+键;
}
}
BT类
{
节根;
公共空白插入(整数k,字符串v)
{
Node newnode=新节点(k,v);
if(root==null)
{
System.out.println(“根”);
根=新节点;
返回;
}
节点n=根;
while(n!=null)
{
如果(newnode.key您从未更改lc
和rc
链接。请尝试以下操作:
if(newnode.key <= n.key)
{
if(n.lc==null){n.lc = newnode; break;}
n = n.lc;
System.out.println("left");
}
else
{
if(n.rc==null){n.rc = newnode; break;}
n = n.rc;
System.out.println("right");
}
if(newnode.key使用递归怎么样?实现起来要清楚得多
public final class BinaryTree {
private static final boolean ADD_TO_PARENT = true;
private static final boolean ALREADY_ADDED = false;
private Node root;
public void add(int key, String value) {
Node node = new Node(key, value);
if (add(node, root) == ADD_TO_PARENT)
root = node;
}
private static boolean add(Node node, Node parent) {
if (parent == null)
return ADD_TO_PARENT;
if (node.key <= parent.key) {
if (add(node, parent.left) == ADD_TO_PARENT)
parent.left = node;
} else if (add(node, parent.right) == ADD_TO_PARENT)
parent.right = node;
return ALREADY_ADDED;
}
public static final class Node {
private final int key;
private final String value;
private Node left;
private Node right;
public Node(int key, String value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return value + " is " + key;
}
}
}
公共最终类二进制树{
私有静态最终布尔值ADD_TO_PARENT=true;
私有静态最终布尔值已添加=false;
私有节点根;
公共void add(int键,字符串值){
节点=新节点(键、值);
if(添加(节点,根)=将\u添加到\u父节点)
根=节点;
}
私有静态布尔添加(节点、节点父节点){
如果(父项==null)
返回添加到父项;
如果(node.keyn=n.lc;
然后n=newnode
没有做你认为它做的事情。只要做n.lc=newnode
并且在你需要继续的时候做n=n.lc
就行了,而不是在你找到节点的时候。当然,这对于n.rc
也是一样的。请参阅以了解对这个问题的不同看法。