二叉树的创建和三种遍历方式
2015-11-12 18:41
316 查看
public class BinaryTree {
public static void main(String[] args)
{
int[] arr = {2,4,6,8,22,34,77,44};
BinaryTree bt = new BinaryTree();
for(int i=0;i<arr.length;i++)
{
bt.buildTree(bt.root, arr[i]);
}
bt.preOrder(bt.root);
bt.inOrder(bt.root);
bt.postOrder(bt.root);
}
private static Node root;
private class Node{
private Node left;
private Node right;
private int data;
public Node(int data)
{
this.data = data;
}
}
public BinaryTree()
{
this.root = null;
}
public static void buildTree(Node node,int data)
{
if(root==null)
{
root = new Node(data);
}
else
{
if(data<node.data)
{
if(node.left==null)
node.left = new Node(data);
else
buildTree(node.left,data);
}
else if(data>node.data)
{
if(node.right==null)
node.right = new Node(data);
else
buildTree(node.right,data);
}
}
}
public static void preOrder(Node node)//前序遍历
{
if(node!=null)
{
System.out.println(node.data);
preOrder(node.left);
preOrder(node.right);
}
}
public static void inOrder(Node node)//中序遍历
{
if(node!=null)
{
inOrder(node.left);
System.out.println(node.data);
inOrder(node.right);
}
}
public static void postOrder(Node node)//后序遍历
{
if(node!=null)
{
postOrder(node.left);
postOrder(node.right);
System.out.println(node.data);
}
}
}
public static void main(String[] args)
{
int[] arr = {2,4,6,8,22,34,77,44};
BinaryTree bt = new BinaryTree();
for(int i=0;i<arr.length;i++)
{
bt.buildTree(bt.root, arr[i]);
}
bt.preOrder(bt.root);
bt.inOrder(bt.root);
bt.postOrder(bt.root);
}
private static Node root;
private class Node{
private Node left;
private Node right;
private int data;
public Node(int data)
{
this.data = data;
}
}
public BinaryTree()
{
this.root = null;
}
public static void buildTree(Node node,int data)
{
if(root==null)
{
root = new Node(data);
}
else
{
if(data<node.data)
{
if(node.left==null)
node.left = new Node(data);
else
buildTree(node.left,data);
}
else if(data>node.data)
{
if(node.right==null)
node.right = new Node(data);
else
buildTree(node.right,data);
}
}
}
public static void preOrder(Node node)//前序遍历
{
if(node!=null)
{
System.out.println(node.data);
preOrder(node.left);
preOrder(node.right);
}
}
public static void inOrder(Node node)//中序遍历
{
if(node!=null)
{
inOrder(node.left);
System.out.println(node.data);
inOrder(node.right);
}
}
public static void postOrder(Node node)//后序遍历
{
if(node!=null)
{
postOrder(node.left);
postOrder(node.right);
System.out.println(node.data);
}
}
}
相关文章推荐
- ajaxfileupload.js异步上传图片
- (java)Majority Element
- hdu2032
- poj-2250Compromise(LCS+标记数组)
- Google Chrome浏览器下开启禁用缓存和js跨域限制disable-application-cache
- Linux 强大的nohup(进程后台执行)
- 【调试】Core Dump是什么?Linux下如何正确永久开启?
- [Andorid开发艺术探索 读书笔记]Activity的生命周期和启动模式 (一)
- hdu2029
- 【调试】Core Dump是什么?Linux下如何正确永久开启?
- 设计模式之桥接模式
- C语言中更改控制台中文字颜色
- JavaWeb学习笔记--HTTP协议
- 配置Java Web中文乱码的过滤器
- MySQL学习笔记(一)MAC系统下 MySQL服务启用、停止、卸载
- APP后端处理表情的一些技巧
- eclipse 同一个package 有的文件 中文乱码,有的文件中文正常
- 利用viewPager实现的自动滑动的广告栏
- 为什么要用EL+JSP标签而不用JSP脚本
- CSDN Markdown简明教程3-表格和公式