Java中的简单二叉搜索树
这里有Java中一个简单的Java中的简单二叉搜索树,java,data-structures,Java,Data Structures,这里有Java中一个简单的BST的代码,键只有int,但是当我想测试它并使用print()时,只需root即可。可以打印键和root。右键和根键。左键是null public class BST { private class Node { private int key; private Node left, right; public Node(int key) { this.key = key;
BST
的代码,键只有int
,但是当我想测试它并使用print()
时,只需root即可。可以打印键和root。右键和根键。左键是null
public class BST {
private class Node {
private int key;
private Node left, right;
public Node(int key) {
this.key = key;
}
}
private Node root;
public BST(int key) {
root = new Node(key);
}
public void insert(int key) {
insert(root, key);
}
private void insert(Node x, int key) {
if (x == null) {
x = new Node(key);
}
if (key > x.key) {
insert(x.right, key);
} else if (key < x.key) {
insert(x.left, key);
} else {
x.key = key;
}
}
public void print() {
print(root);
}
private void print(Node x) {
System.out.print(x.key + " ");
if (x.left != null)
print(x.left);
if (x.right != null)
print(x.right);
}
}
公共类BST{
私有类节点{
私钥;
私有节点左、右;
公共节点(int键){
this.key=key;
}
}
私有节点根;
公共BST(整型密钥){
根=新节点(键);
}
公共无效插入(int键){
插入(根,键);
}
私有void插入(节点x,int键){
如果(x==null){
x=新节点(键);
}
如果(键>x键){
插入(x.右侧,键);
}否则如果(键
例如,当我插入25、9、10、30、40并调用print()
时,它只打印25
x = new Node(key);
这个赋值基本上丢弃了新节点
,因为x
只是一个局部变量。您没有在此处修改呼叫者引用,您只是修改呼叫者提供给您的引用的本地副本。您可以做的是返回x
并让调用者分配它:
x = insert(x, 3);
insert
将如下所示:
private Node insert(Node x, int key) {
if (x==null){
return new Node(key);
}
if (key > x.key) {
x.right = insert(x.right, key);
}else if (key < x.key) {
x.left = insert(x.left, key);
}else{
x.key = key;
}
return x;
}
专用节点插入(节点x,int键){
如果(x==null){
返回新节点(键);
}
如果(键>x键){
x、 右=插入(x.右,键);
}否则如果(键
这个赋值基本上丢弃了新节点
,因为x
只是一个局部变量。您没有在此处修改呼叫者引用,您只是修改呼叫者提供给您的引用的本地副本。您可以做的是返回x
并让调用者分配它:
x = insert(x, 3);
insert
将如下所示:
private Node insert(Node x, int key) {
if (x==null){
return new Node(key);
}
if (key > x.key) {
x.right = insert(x.right, key);
}else if (key < x.key) {
x.left = insert(x.left, key);
}else{
x.key = key;
}
return x;
}
专用节点插入(节点x,int键){
如果(x==null){
返回新节点(键);
}
如果(键>x键){
x、 右=插入(x.右,键);
}否则如果(键