您的位置:首页 > 编程语言 > Java开发

二叉查找树的java实现

2015-08-13 19:29 531 查看
package TestBinarySearchTree;

/**
* Created by yanzan.lyw on 2015/8/7.
*/

public class BinarySearchTree {

static private class Node{
int val;
Node nodeLeft;
Node nodeRight;
public Node(int val, Node nodeLeft, Node nodeRight){
this.val = val;
this.nodeLeft = nodeLeft;
this.nodeRight = nodeRight;
}

public int getVal() {
return val;
}

public void setVal(int val) {
this.val = val;
}

public Node getNodeLeft() {
return nodeLeft;
}

public void setNodeLeft(Node nodeLeft) {
this.nodeLeft = nodeLeft;
}

public Node getNodeRight() {
return nodeRight;
}

public void setNodeRight(Node nodeRight) {
this.nodeRight = nodeRight;
}

}

private Node rootNode;

public BinarySearchTree(){
rootNode = null;
}

public boolean insertNode(int val){
if (null == rootNode){
rootNode = new Node(val, null, null);
return true;
}
return insertNode(rootNode, val);
}

public void printVals(){
printVals(rootNode);
}

public boolean findVal(int val){
return findVal(rootNode, val);
}

private boolean insertNode(final Node node, final int val){
if (val == node.val){
return false;
}

if (val > node.val){
if (null == node.getNodeRight()){
node.setNodeRight(new Node(val, null, null));
return true;
}else {
return insertNode(node.getNodeRight(), val);
}
}

if (val < node.val){
if (null == node.getNodeLeft()){
node.setNodeLeft(new Node(val, null, null));
return true;
}else {
return insertNode(node.getNodeLeft(), val);
}
}
return true;
}

private void printVals(Node node){
if (null == node){
return;
}

printVals(node.getNodeLeft());
System.out.println(node.val);
printVals(node.getNodeRight());
}

public boolean findVal(final Node node, final int val){
if (null == node){
return false;
}

if (val == node.val){
return true;
}

if (val > node.val){
return findVal(node.getNodeRight(), val);
}

if (val < node.val){
return findVal(node.getNodeLeft(), val);
}

return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: