gpt4 book ai didi

Java BST 递归

转载 作者:行者123 更新时间:2023-11-30 07:09:29 25 4
gpt4 key购买 nike

我最近从 C++ 转向了 Java,现在我正在研究 C++ 中需要使用指针的数据结构。

我现在正在 Java 中创建 BST,我使用递归插入到 Tree 中,但它没有像我预期的那样工作。此代码仅存储带有 val = 5Node。你能给我什么建议吗?

public class Main
{
public static void main( String [] args )
{
BST<Integer> bst = new BST<Integer>();
bst . add( 5 );
bst . add( 10 );
}
}

public class BST<T extends Number & Comparable<T>>
{
private Node root;

private class Node
{
private T val;
private Node left;
private Node right;

Node(T val)
{
this . val = val;
left = null;
right = null;
}
}


public BST()
{
root = null;
}

public BST( T val )
{
root = new Node( val );
}

public void add( T val )
{
if( root == null )
root = new Node(val);
else
add( root, val );
}

private void add( Node parent, T val )
{
if( parent == null )
parent = new Node(val);
else if( val . compareTo( parent . val ) < 0 )
add( parent . left, val );
else if( val . compareTo( parent . val ) > 0 )
add( parent . right, val );
}
}

谢谢。

最佳答案

Java 是按引用传递的,因此执行 parent = new Node(val) 不会取得任何效果。您只是更改本地参数。

您需要执行类似 if ( left == null ) left = new Node(val) else add (left,val) 的操作。

不发布代码,因为这可能是一个家庭作业问题。

关于Java BST 递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39452174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com