java实现二叉树
2016-04-18 21:21
369 查看
用java实现实现二叉树
第一步:创建节点类
//构造二叉树
//测试并输出
第一步:创建节点类
<span style="font-size:18px;">class TreeNode { private Object nodeValue; private TreeNode left, right; public TreeNode(){ this(null, null, null); } public TreeNode(Object item){ nodeValue = item; } public TreeNode(Object item, TreeNode left, TreeNode right){ nodeValue = item; this.left = left; this.right = right; } //判断当前节点是否为叶子 public boolean isEmpty(){ if (this.left == null && this.left == null){ return true; } return false; } //重写toString方法 public String toString(){ if (nodeValue == null){ return null; } String result = "(节点" + nodeValue.toString(); if (left != null){ result += "左节点" + left.toString(); } if (right != null){ result += "右节点" + right.toString(); } result += ")"; return result; } } //实现二叉树 class BinaryTree { protected TreeNode root;//定义一个节点对象成员 public BinaryTree(){ root = null; } public BinaryTree(TreeNode root){ this.root = root; } public boolean isEmpty(){ return this.root == null; } public TreeNode getRoot(){ return root; } public String toString(){ return root.toString(); } } 实现如图所示的二叉树 <img src="http://img.blog.csdn.net/20160418211703770?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" height="259" width="572" /> </span>
//构造二叉树
<span style="font-size:18px;">public class BulidBinaryTree { public static BinaryTree creat(){ TreeNode a, b, c, d, e, f, g; //创建叶子 f = new TreeNode("F"); g = new TreeNode("G"); d = new TreeNode("D"); c = new TreeNode("C"); //创建根节点 e = new TreeNode("E", f, g); b = new TreeNode("B", d, e); a = new TreeNode("A", b, c); return new BinaryTree(a); } } </span>
//测试并输出
<span style="font-size:18px;">public class TestDemo { public static void main(String[] args) { BinaryTree binaryTree = BulidBinaryTree.creat(); System.out.println(binaryTree); } } 结果如下 </span>
相关文章推荐
- JAVA正则表达式:Pattern类与Matcher类详解(转)
- 3.Java之运算符
- JAVA-继承和接口
- Java运算符优先级问题
- 如何在Ubuntu 14.04中安装最新版Eclipse
- Ubuntu下Eclipse安装SVN插件(Subversion & Subclipse)
- maven 项目 cxf+spring 发布rest风格webservice
- Ubuntu下Eclipse的安装方法(图文详解)
- Java运算符问题
- java毕向东听课笔记17(字符串1)
- java实现MD5加密
- eclipse 小技巧
- java发送邮件工具类
- Java实现MD5加密
- JAVA递归全排列
- 设计模式----适配器模式
- java 反射机制
- java设计模式
- JDK 1.7 1.8 新特性
- Java算法学习之旅-算法基本概念