【发布时间】:2014-05-12 23:22:45
【问题描述】:
我正在为我一直从事的项目创建二叉树,我在其中按名称将人员插入二叉树(树遍历每个字符以确定插入时哪个更大)。有没有办法让我的树在树中搜索以找到与程序的名称相匹配的人。这是我目前的代码
lass Node {
private String person;
private Node left;
private Node right;
public Node(String person) {
this.person = person;
left = null;
right = null;
}
//setters
protected void setLeft(Node left) {
this.left = left;
}
protected void setRight(Node right) {
this.right = right;
}
//getters
protected String getPerson() {
return person;
}
protected Node getLeft() {
return left;
}
protected Node getRight() {
return right;
}
}
public class BinaryTree {
private static Node root;
public BinaryTree() {
root = null;
}
public void insert(String person) {
root = insert(person, root);
}
//Check if node is leaf
public static boolean isLeaf() {
if(root.getLeft() == null && root.getRight() == null)
return false;
else
return true;
}
// Search tree for entered value
public static void searchTree(String search, Node tNode) {
// Not sure what to put into the part to make the method search through people in the tree
}
private Node insert(String person, Node tree) {
if(tree == null)
tree = new Node(person);
else {
int count = 1;
int x = 0;
while(person.toLowerCase().charAt(x) == tree.getPerson().toLowerCase().charAt(x) && count != tree.getPerson().length()) {
count = count + 1;
x = x + 1;
}
if(person.toLowerCase().charAt(x) != tree.getPerson().toLowerCase().charAt(x)) {
if(person.toLowerCase().charAt(x) < tree.getPerson().toLowerCase().charAt(x))
tree.setLeft(insert(person, tree.getLeft()));
else
tree.setRight(insert(person, tree.getRight()));
} else {
tree.setRight(insert(person, tree.getRight()));
}
}
return tree;
}
您能否建议我应该如何创建一种搜索树的方法
【问题讨论】:
标签: java search tree binary-tree binary-search-tree