您的位置:首页 > 理论基础 > 数据结构算法

java与数据结构--二叉树

2018-10-17 16:33 99 查看
[code]package myFirstJava;
import java.util.*;

public class BinaryTree {
private static node head = null;
private static StringBuffer s = new StringBuffer();
private static int count = 0;
/////creat a binarytree
private static  node creatTree(node point){

Scanner sc = new Scanner(System.in);

int val = sc.nextInt();
point= new node(val);
s.append(val);

//为0时表明叶子节点
if(val != 0){

point.lChild = creatTree(point.lChild);
point.rChild = creatTree(point.rChild);
}
return point;
}

/////show a binarytree
private static void showTree(node point,int type){

if(point!=null){

switch (type){
case 1:
////前序遍历  把问题细化,无论递归如何本质就是深度搜索与回溯的过程;

System.out.print(point.val);
System.out.print(" ");
showTree(point.lChild, 1);
showTree(point.rChild, 1);
break;

case 2:
////中序遍历

showTree(point.lChild, 2);
System.out.print(" ");
System.out.print(point.val);
showTree(point.rChild, 2);
break;

case 3:
//// 后序遍历

showTree(point.lChild, 2);
System.out.print(" ");
System.out.print(point.val);
showTree(point.rChild, 2);
break;

case 4:
//// 层级遍历  使用队列的方法,利用队列的先进先出特性,跟换队列的队首元素
LinkedList queue = new LinkedList();
queue.add(point);
Iterator li = queue.iterator();

while(queue.size()>0){

node p = (node)queue.getFirst();

System.out.print(p.val + " ");
////集合方法返回对象,需要强制类型转换为node
if(p.lChild!=null)
queue.addLast(p.lChild);
if(p.rChild!=null)
queue.addLast(p.rChild);
queue.removeFirst();
}
}
}
return ;
}
///搜索二叉树的最大深度,把问题细化,简单化
private int TreeDepth(node point){
int ldep,rdep;
if(point == null)
return 0;
else{
ldep = TreeDepth(point.lChild);
rdep = TreeDepth(point.rChild);
return ldep>rdep? ldep+1:rdep+1;
}
}
///统计叶子节点数目
private  static void Leafnum(node point){

if(point!=null){
if(point.lChild==null && point.rChild==null)
count++;
Leafnum(point.lChild);
Leafnum(point.rChild);
}

}

public static void main(String[] args){

head = creatTree(head);
showTree(head, 4);
Leafnum(head);
System.out.println("\n\nthe leafs quantity is " + count);
}
}

class node{
int val;
node(int val){
this.val = val;
}
public  node lChild,rChild;
}

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: