package cn.xiaobo.BinearyTree;node
public class BinearyTreeApp {post
private Node root;
public BinearyTreeApp() {
this.root=null;
}
public Node getRoot() {
if(root!=null){
return root;
}
return null;
}
public void insert(int id) {
Node newNode=new Node(id);
//若是什麼都沒有插入,新節點就是根節點;
if(root==null){
root=newNode;
}else {
Node current=root;
Node abovenode;
//在一個死循環裏找到要插入的位置
while(true){
//abovenode的做用是當current爲null時,abovenode就是上一個節點
//能夠把新節點插入;
abovenode=current;
if(id>current.id){
current=current.RightNode;
if(current==null){
abovenode.RightNode=newNode;
//結束死循環
return;
}
}
else{
current=current.LeftNode;
if(current==null){
abovenode.LeftNode=newNode;
return;
}
}
}
}
}
public Node delete(int id) {
return null;
}
public Node find(int key) {
Node current=root;
//在循環中找到對應的key;
while(key!=current.id){
//大於key的數據在右邊;
if(key>current.id){
current=current.RightNode;
}
//小於key的節點在左邊
else{
current=current.LeftNode;
}
//若是找不到就是爲null;
if(current==null){
return null;
}
}
return current;
}
//只要將跟節點傳入就行,
//中序遍歷是訪問左邊再訪問中間再訪問右邊的方法;
public void inOrder(Node root) {
if(root!=null){
//遞歸調用傳進的節點的左邊
inOrder(root.LeftNode);
//打印傳進的節點id
System.out.println("Node is: "+root.id);
//遞歸調用傳進的節點的右邊
inOrder(root.LeftNode);
return;
}
}
//只要將跟節點傳入就行
//前序遍歷是先跟節點再訪問左邊,右邊
public void preOrder(Node root) {
if(root!=null){
//打印傳進的節點id
System.out.println("Node is: "+root.id);
//遞歸調用傳進的節點的左邊
inOrder(root.LeftNode);
//遞歸調用傳進的節點的右邊
inOrder(root.LeftNode);
return;
}
}
//只要將跟節點傳入就行
//後序遍歷是根節點最後訪問
public void postOrder(Node root) {
if(root!=null){
//遞歸調用傳進的節點的左邊
inOrder(root.LeftNode);
//遞歸調用傳進的節點的右邊
inOrder(root.LeftNode);
//打印傳進的節點id
System.out.println("Node is: "+root.id);
return;
}
}this
}spa
package cn.xiaobo.BinearyTree;遞歸
public class Node {get
public int id;
public Node LeftNode;
public Node RightNode;
public Node(int id) {
this.id=id;
this.LeftNode=null;
this.RightNode=null;
}
}class
package cn.xiaobo.BinearyTree;循環
public class BinearyTreeMain {遍歷
public static void main(String[] args) {
BinearyTreeApp binearyTreeApp=new BinearyTreeApp();
binearyTreeApp.insert(23);
binearyTreeApp.insert(12);
binearyTreeApp.insert(34);
binearyTreeApp.insert(345);
binearyTreeApp.insert(11);
binearyTreeApp.insert(3);
binearyTreeApp.insert(56);
Node root=binearyTreeApp.getRoot();
System.out.println("root is: "+root.id);
System.out.println("inOrder is: ");
binearyTreeApp.inOrder(root);
System.out.println("preOrder is: ");
binearyTreeApp.preOrder(root);
}
}方法