package com.lidong4;
import java.util.*;
public class Tree {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]={12,11,34,45,67,38,56,43,22,8};
Node root=new Node(arr[0]);
for(int i=1;i<arr.length;i++){
root.insertNode(root, new Node(arr[i]));
}
ArrayList<Node> lis=new ArrayList<Node>();
lis.add(root);
root.show(lis);
root.getKey(67, root);
// root.leftShow(root);
//root.midShow(root);
root.rightShow(root);
}
}
class Node{
int data;
Node leftpointer;
Node rightpointer;
public Node(int data){
this.data=data;
//this.leftpointer=null;
//this.rightpointer=null;
}
public int getdata(){
return data;
}
public void insertNode(Node subNode,Node newNode){
while(true){
if(subNode.data>newNode.data){
if(subNode.leftpointer==null){
subNode.leftpointer=newNode;
break;
}else{
subNode=subNode.leftpointer;
}
}else{
if(subNode.rightpointer==null){
subNode.rightpointer=newNode ;
break;
}else{
subNode=subNode.rightpointer;
}
}
}
}
public void show(ArrayList<Node> nodes){
if(nodes==null||nodes.size()==0){
return;
}
ArrayList<Node> temp=new ArrayList<Node>();
for(Node i:nodes){
System.out.print(i.getdata()+" ");
if(i.leftpointer!=null){
temp.add(i.leftpointer);
}
if(i.rightpointer!=null){
temp.add(i.rightpointer);
}
}
System.out.println();
nodes.removeAll(nodes);
show(temp);
}
public void getKey(int key,Node root){
Node result=root;
while(result.data!=key){
if(key<result.data){
result=result.leftpointer;
}else{
result=result.rightpointer;
}
if(result==null){
System.out.println("找不到此数!");
break;
}
}
//System.out.println("找到此数!");
}
public void leftShow(Node root){
if(root!=null){
System.out.print(root.data+" ");
leftShow(root.leftpointer);
leftShow(root.rightpointer);
}
}
public void midShow(Node root){
if(root!=null){
midShow(root.leftpointer);
System.out.print(root.data+" ");
midShow(root.rightpointer);
}
}
public void rightShow(Node root){
if(root!=null){
rightShow(root.leftpointer);
rightShow(root.rightpointer);
System.out.print(root.data+" ");
}
}
}