Professional Documents
Culture Documents
Binary Tree in Java
Binary Tree in Java
Noderoot;
publicvoidaddNode(intkey,Stringname){
//CreateanewNodeandinitializeit
NodenewNode=newNode(key,name);
//Ifthereisnorootthisbecomesroot
if(root==null){
}else{
//SetrootastheNodewewillstart
//withaswetraversethetree
NodefocusNode=root;
//FutureparentforournewNode
Nodeparent;
while(true){
//rootisthetopparentsowestart
//there
parent=focusNode;
//Checkifthenewnodeshouldgoon
//theleftsideoftheparentnode
if(key<focusNode.key){
//Switchfocustotheleftchild
focusNode=focusNode.leftChild;
//Iftheleftchildhasnochildren
if(focusNode==null){
//thenplacethenewnodeontheleftofit
parent.leftChild=newNode;
return;//AllDone
}else{//Ifwegethereputthenodeontheright
focusNode=focusNode.rightChild;
//Iftherightchildhasnochildren
if(focusNode==null){
root=newNode;
//thenplacethenewnodeontherightofit
//Allnodesarevisitedinascendingorder
//Recursionisusedtogotoonenodeand
//thengotoitschildnodesandsoforth
publicvoidinOrderTraverseTree(NodefocusNode){
if(focusNode!=null){
//Traversetheleftnode
inOrderTraverseTree(focusNode.leftChild);
//Visitthecurrentlyfocusedonnode
System.out.println(focusNode);
//Traversetherightnode
inOrderTraverseTree(focusNode.rightChild);
publicvoidpreorderTraverseTree(NodefocusNode){
if(focusNode!=null){
System.out.println(focusNode);
preorderTraverseTree(focusNode.leftChild);
preorderTraverseTree(focusNode.rightChild);
publicvoidpostOrderTraverseTree(NodefocusNode){
if(focusNode!=null){
postOrderTraverseTree(focusNode.leftChild);
postOrderTraverseTree(focusNode.rightChild);
System.out.println(focusNode);
publicNodefindNode(intkey){
//Startatthetopofthetree
parent.rightChild=newNode;
return;//AllDone
NodefocusNode=root;
//Whilewehaven'tfoundtheNode
//keeplooking
while(focusNode.key!=key){
//Ifweshouldsearchtotheleft
if(key<focusNode.key){
//ShiftthefocusNodetotheleftchild
focusNode=focusNode.leftChild;
}else{
//ShiftthefocusNodetotherightchild
focusNode=focusNode.rightChild;
//Thenodewasn'tfound
if(focusNode==null)
returnnull;
returnfocusNode;
publicstaticvoidmain(String[]args){
BinaryTreetheTree=newBinaryTree();
theTree.addNode(50,"Boss");
theTree.addNode(25,"VicePresident");
theTree.addNode(15,"OfficeManager");
theTree.addNode(30,"Secretary");
theTree.addNode(75,"SalesManager");
theTree.addNode(85,"Salesman1");
//Differentwaystotraversebinarytrees
//theTree.inOrderTraverseTree(theTree.root);
//theTree.preorderTraverseTree(theTree.root);
//theTree.postOrderTraverseTree(theTree.root);
//Findthenodewithkey75
System.out.println("\nNodewiththekey75");
System.out.println(theTree.findNode(75));
}
}
classNode{
intkey;
Stringname;
NodeleftChild;
NoderightChild;
Node(intkey,Stringname){
publicStringtoString(){
returnname+"hasthekey"+key;
/*
*returnname+"hasthekey"+key+"\nLeftChild:"+leftChild+
*"\nRightChild:"+rightChild+"\n";
*/
this.key=key;
this.name=name;