package com.yu.datastructure.tree;
import java.util.HashSet;
import java.util.Set;
//二叉树 自动排序 左子树所有节点小于或者等于root节点 右子树所有节点比root节点大
class BinaryTree{
private int data;
private BinaryTree left;
private BinaryTree right;
private BinaryTree root;
public void addNode(int d){
//第一次初始化根节点
if(root == null){
root = new BinaryTree();
root.data = d;
//找到合适的位置插入
}else{
insert(root , d);
}
}
private void insert(BinaryTree root , int d){
//待插入数据小于根节点找到左子树为空的节点 插入数据
if(d <= root.data && root.left != null){
insert( root.left ,d);
}else if(d <= root.data && root.left == null){
BinaryTree t = new BinaryTree();
t.data = d;
t.left = null; t.right = null;
root.left = t;
//待插入数据大于根节点找到右子树为空的节点 插入数据
}else if(d > root.data && root.right != null){
insert( root.right ,d);
}else if(d > root.data && root.right == null){
BinaryTree t = new BinaryTree();
t.data = d;
t.left = null; t.right = null;
root.right = t;
}
}
public void print(){
printNode(root);
}
//因为是排序后的树 使用中序 遍历
private void printNode(BinaryTree root){
if(root.left != null)
printNode(root.left);
if(root!=null)
System.out.println(root.data);
if(root.right != null)
printNode(root.right);
}
}
class Student{
private int age;
private String name;
public Student(int age, String name){
this.age = age;
this.name = name;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
Student s = (Student)obj;
return s.name.equals(name) && s.age == this.age;
}
@Override
public int hashCode() {
return age;
}
}
public class TreeTest {
public static void main(String[] args) {
BinaryTree b = new BinaryTree();
b.addNode(6);
b.addNode(6);
b.addNode(3);
b.addNode(1);
b.addNode(4);
b.addNode(8);
b.addNode(7);
b.addNode(9);
b.print();
}
}