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; }
阅读更多
相关文章推荐
- 重温数据结构:二叉树的常见方法及三种遍历方式 Java 实现
- java数据结构之二叉树的遍历
- 【数据结构】之二叉树的java实现
- 数据结构 二叉树的重构(java实现)
- 数据结构:二叉树(JAVA实现)
- java数据结构--二叉树与查找树
- 【数据结构】之二叉树的java实现
- JAVA数据结构:二叉树
- 【数据结构】之二叉树的java实现
- java数据结构之二叉树
- 数据结构(JAVA)---二叉树的简单实现及排序
- JAVA数据结构---二叉树入门
- Java数据结构-二叉树及其遍历
- (2)Java数据结构--二叉树 -和排序算法实现
- 数据结构 — 二叉树(创建、遍历)java实现
- JAVA数据结构---二叉树入门
- JAVA 数据结构 二叉树
- java--数据结构--二叉树的最近公共祖先
- 【数据结构】之二叉树的java实现
- java--数据结构--二叉树根节点到指定节点的路径