直接上代码
public class BinaryTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
BinaryTreeDemo binaryTreeDemo=new BinaryTreeDemo();
binaryTreeDemo.add(9);
binaryTreeDemo.add(7);
binaryTreeDemo.add(8);
binaryTreeDemo.add(12);
binaryTreeDemo.add(14);
binaryTreeDemo.add(13);
binaryTreeDemo.add(5);
binaryTreeDemo.add(4);
binaryTreeDemo.add(6);
binaryTreeDemo.add(15);
binaryTreeDemo.print();
System.out.println();
System.out.println(binaryTreeDemo.getMin());
System.out.println(binaryTreeDemo.find(15));
}
}
class BinaryTreeDemo{
private Node root;
public void add(int date){
if(root==null){
root=new Node(date);
}else {
root.add(date);
}
}
public void print(){
if(root==null){
return;
}else {
root.print();
}
}
public boolean find(int date){
if(root!=null){
return root.find(date);
}else{
//System.out.println("123");
return false;
}
}
public Node getMin(){
if(root==null){
return null;
}else {
return root.getMin();
}
}
class Node{
private int date;
private Node leftNode;
private Node rigNode;
public Node(int date){
this.date=date;
}
public Node() {
super();
// TODO Auto-generated constructor stub
}
public int getDate() {
return date;
}
public void setDate(int date) {
this.date = date;
}
public Node getLeftNode() {
return leftNode;
}
public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}
public Node getRigNode() {
return rigNode;
}
public void setRigNode(Node rigNode) {
this.rigNode = rigNode;
}
public String toString() {
return "Node [date=" + date + "]";
}
public void add(int date){
if(this.getDate()<date){
if (this.rigNode==null) {
this.rigNode=new Node(date);
} else {
this.rigNode.add(date);
}
}else{
if (this.leftNode==null) {
this.leftNode=new Node(date);
}else {
this.leftNode.add(date);
}
}
}
public void print(){
if(this.leftNode!=null){
this.leftNode.print();
}
System.out.print(this.getDate()+" ");
if(this.rigNode!=null){
this.rigNode.print();
}
}
public Node getMin(){
if(this.leftNode==null){
return this;
}else {
return this.leftNode.getMin();
}
}
public boolean find(int date){
if(this.getDate()==date){
return true;
}else {
if(this.getDate()<date){
if(this.rigNode==null){
return false ;
}else {
return this.rigNode.find(date);
}
}else {
if(this.leftNode==null){
return false;
}else{
return this.leftNode.find(date);
}
}
}
}
}
}