Java语言实现二叉树
来源:互联网 发布:java中如何使用debug 编辑:程序博客网 时间:2024/06/05 10:04
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; }}
1 0
- Java语言实现二叉树
- 二叉树的实现(Java语言描述)
- 平衡二叉树Java语言实现
- 二叉树之用java语言实现
- 数据结构-二叉树 JAVA语言实现
- java 语言实现二叉树的各种操作
- 用Java语言实现二叉树的结点插入
- 用Java语言实现二叉树删除结点
- 二叉搜索树的实现(Java语言)
- Data structure-5 二叉搜索树 BST--Java语言实现
- C语言实现二叉树
- C语言实现二叉树
- C语言实现二叉树
- C语言实现二叉树
- JAVA 实现二叉树
- 二叉树 java实现
- 二叉树实现-java
- JAVA 实现二叉树。
- java synchronized详解
- php中使用redis
- Flume核心概念
- Android音频通讯
- 线性表的两种实现 -- 顺序表和链表(C++)
- Java语言实现二叉树
- java Object转Map 小工具
- TCP的状态(SYN,FIN,ACK,PSH,RST,URG)
- 文件重命名批量处理(Matlab)
- PDF文件如何转换成Excel
- (第18讲)java数据结构的堆栈与内存区的堆栈(总结各大神的见解)
- Retrofit 入门和提高
- Sublime Text 使用介绍、全套快捷键及插件推荐
- 微信硬件平台的基础接入和硬件云标准接入分析