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);
}
}方法