二叉查找树的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; } }
相关文章推荐
- HBase1.0.1基本操作(java代码)
- 快速排序,归并排序,堆排序的java代码实现
- 使用Spring框架的步骤
- 精通Hibernate——Hibernate中Java对象的状态详解
- 懒得笔记4 spring annotation
- [Java] Majority Element II 找众数2
- eclipse启动报错A Java RunTime Environment (JRE) or Java Development Kit (JDK) must be available in order to run Eclipse.
- 深入理解java的finalize
- Eclipse ADT的Custom debug keystore所需证书规格
- [Java] Majority Element (求过半数,或者翻译成 求出现次数过半的众数)
- Java的反射机制
- 修改eclipse默认workspace
- 【Head First Java 读书笔记】(三)primitive主数据类型和引用
- java dom解析xml
- (转)Eclipse快捷键
- Java中Filter、Servlet、Listener
- Java SE 学习笔记(二)
- java两个线程打印奇数和偶数
- Eclipse远程调试java web应用
- java大数 hdu5241