Einführung
in die objektorientierte Programmierung
Überprüfung, ob ein binärer Baum ein SearchTree ist (sortiert) mit drei Methoden
import java.util.*;
class BinaryTreeNode{
private int entry;
private BinaryTreeNode leftChild;
private BinaryTreeNode rightChild;
static int alt=0;
static int neu=0;
static ArrayList<Integer> liste = new ArrayList<Integer>();
public int getEntry(){
return entry;
}
public BinaryTreeNode getLeft(){
return leftChild;
}
public BinaryTreeNode getRight(){
return rightChild;
}
public void setEntry(int e){
entry=e;
}
public void setLeft(BinaryTreeNode e){
leftChild=e;
}
public void setRight(BinaryTreeNode e){
rightChild=e;
}
static public void inorder(BinaryTreeNode node){
if (node != null) {
inorder(node.getLeft());
//System.out.println(node.getEntry());
liste.add(node.getEntry());
inorder(node.getRight());
} // end of if
}
static public boolean isSearchTree(BinaryTreeNode node){
int alt =0;
int neu =0;
inorder(node);
for (Integer wert : liste ) {
neu= wert;
if (alt>neu) {
return false;
} // end of if
System.out.println(wert);
alt=neu;
} // end of for
return true;
}
static public boolean isSearchTree2(BinaryTreeNode node){
if (node == null) {
return true;
}
if (isSearchTree2(node.getLeft())==false) return false;
neu=node.getEntry();
System.out.println(node.getEntry());
if (alt>neu) return false;
alt=neu;
if (isSearchTree2(node.getRight())==false) return false;
return true;
}
static public boolean isSearchTree3(BinaryTreeNode old,
BinaryTreeNode node){
if (node == null) {
return true;
}
if (isSearchTree3(old,node.getLeft())==false) return false;
System.out.println(node.getEntry());
if (old.entry>node.entry) return false;
old.entry=node.entry;
if (isSearchTree3(old,node.getRight())==false) return false;
return true;
}
static public int getMaximum(BinaryTreeNode node){
if (node==null) {
return 0;
} // end of if
while (node.getRight()!= null) {
node=node.getRight();
} // end of while
return node.getEntry();
}
public static void main(String[] args){
BinaryTreeNode root= new BinaryTreeNode();
root.setEntry(5);
BinaryTreeNode neu= new BinaryTreeNode();
neu.setEntry(3);
root.setLeft(neu);
neu.setRight(new BinaryTreeNode());
neu.getRight().setEntry(4);
neu= neu.getRight();
neu.setLeft(new BinaryTreeNode());
neu.getLeft().setEntry(4);
neu.setRight(new BinaryTreeNode());
neu.getRight().setEntry(5);
root.setRight(new BinaryTreeNode());
root.getRight().setEntry(7);
//root=null;
System.out.println(BinaryTreeNode.isSearchTree(root));
System.out.println();
System.out.println(BinaryTreeNode.isSearchTree2(root));
System.out.println();
BinaryTreeNode old = new BinaryTreeNode();
old.setEntry(0);
System.out.println(BinaryTreeNode.isSearchTree3(old,root));
System.out.println();
//System.out.println(BinaryTreeNode.getMaximum(root));
}
}