package tree;
public class BinartSearchtree {
private Node root;
public BinartSearchtree(Node root) {
super();
this.root = root;
}
public Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
public BinartSearchtree() {
root=null;
}
public void insearch(int x) {
if(root==null) {
root=new Node(x);
return;
}
Node p=root;
while (p!=null) {
if(x>p.getData()) {
if(p.getRight()==null) {
p.setRight(new Node(x));
return;
}
p=p.getRight();
}
else {
if (p.getLeft()==null) {
p.setLeft (new Node(x));
return;
}
p=p.getLeft();
}
}
}
public Node find(int x) {
Node p=root;
while(p!=null) {
if(x>p.getData()) {
p=p.getRight();
}
else if(x<p.getData()) {
p=p.getLeft();
}
else {
return p;
}
}
return null;
}
public void preorder() {
System.out.println("先序遍历:");
preorder(root);
}
public void preorder(Node p) {
if(p!=null) {
System.out.print(p.getData()+" ");
preorder(p.getLeft());
preorder(p.getRight());
}
}
public Node minNode(Node p) {
// Node p=root;
while(p.getLeft()!=null) {
p=p.getLeft();
}
return p;
}
public Node maxNode(Node p) {
// Node p=root;
while(p.getRight()!=null) {
p=p.getRight();
}
return p;
}
// public Node delete(int x, Node p) {
// Node temp;
// if(p==null) {
// System.out.println("error");
// return null;
// }
// else if () {
//
// }
// }
public static void main(String[] args) {
BinartSearchtree mytree1= new BinartSearchtree();
int[] arr= {6,3,8,1,4,2};
for (int i = 0; i < arr.length; i++) {
mytree1.insearch(arr[i]);
}
mytree1.preorder();
System.out.println();
System.out.println(mytree1.find(8));
System.out.println(mytree1.minNode(mytree1.root) );
System.out.println(mytree1.maxNode(mytree1.root) );
// TODO Auto-generated method stub
}
}
创建二叉搜索树,先序中序后序遍历,查找某个节点,找最小节点和最大节点
猜你喜欢
转载自blog.csdn.net/weixin_45116412/article/details/104927092
今日推荐
周排行