Java语言实现二叉树
2016-05-27 10:59
441 查看
Java语言实现二叉树
代码
import java.util.Scanner; /** * Java语言实现的二叉树结构 * 原理分析 主要采用递归思想 * * @author tuzhao * @github tuzhao * @mail tuzhaocn@gmail.com */ public class BinaryTree { public static class Node { int item; int count; Node pLeft; Node pRight; } public static void main(String[] args) { int newValue = 0; Node pRoot = null; long answer = 0; Scanner scanner = new Scanner(System.in); do { newValue = 0; System.out.println("please enter the node value: (-2147483648 -- 2147483647)"); newValue = scanner.nextInt(); if (pRoot == null) { pRoot = createNode(newValue); } else { addNode(newValue, pRoot); } answer = 0; System.out.println("do you want to enter another? 1 is yes! 0 is stop!"); answer = scanner.nextLong(); } while (answer == 1); System.out.println("all the intput value is:"); listNodes(pRoot); freeNodes(pRoot); scanner.close(); } public static Node createNode(int v) { Node node = new Node(); node.item = v; node.count = 1; node.pLeft = null; node.pRight = null; return node; } public static Node addNode(int v, Node pNode) { if (pNode == null) { return createNode(v); } if (pNode.item == v) { pNode.count++; return pNode; } if (v < pNode.item) { if (pNode.pLeft == null) { pNode.pLeft = createNode(v); return pNode.pLeft; } else { return addNode(v, pNode.pLeft); } } else { if (pNode.pRight == null) { pNode.pRight = createNode(v); return pNode.pRight; } else { return addNode(v, pNode.pRight); } } } public static void listNodes(Node pNode) { if (pNode.pLeft != null) { listNodes(pNode.pLeft); } for (int i = 0; i < pNode.count; i++) { System.out.println(pNode.item); } if (pNode.pRight != null) { listNodes(pNode.pRight); } } public static void freeNodes(Node pNode) { if (pNode == null) { return; } if (pNode.pLeft != null) { freeNodes(pNode.pLeft); } if (pNode.pRight != null) { freeNodes(pNode.pRight); } pNode = null; } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树