java 二叉树编程 求救

2024-11-24 03:08:12
推荐回答(2个)
回答1:

//给的分有点少哦
public class BTNode {
public String data;
public BTNode left;
public BTNode right;

public BTNode(String data, BTNode l, BTNode r) {
this.data = data;
this.left = l;
this.right = r;
}

public BTNode(String data) {
this.data = data;
}
}

public class BTree {
private BTNode root;

public BTree(){

}

public BTree(BTree t){
CopyNodes(t.root, this);
}

private void CopyNodes(BTNode node, BTree tree){
if(node == null){
return;
}
tree.insert(node.data);
CopyNodes(node.left, tree);
CopyNodes(node.right, tree);
}

public void insert(String newData){
root = insert2(newData, root);
}

private BTNode insert2(String s, BTNode n){
if(n == null){
return new BTNode(s);
}

if(s.compareTo(n.data) < 0){
n.left = insert2(s, n.left);
}else if(s.compareTo(n.data) > 0){
n.right = insert2(s, n.right);
}

return n;
}

public BTNode find(String s){
BTNode node = root;
while(node != null){
if(s.equals(node.data)){
return node;
}
if(s.compareTo(node.data) < 0){
node = node.left;
}else{
node = node.right;
}
}
return null;
}

public void printInOrder(){
showNode(root);
}

private void showNode(BTNode node){
if(node == null){
return;
}
showNode(node.left);
System.out.print(node.data + "\t");
showNode(node.right);
}
}

回答2:

我有C语言的二叉树 要不