设为首页 加入收藏

TOP

Java实现根据前序遍历构建二叉树(前序遍历、中序遍历、后序遍历)
2014-11-24 02:29:30 来源: 作者: 【 】 浏览:1
Tags:Java 实现 根据 构建 后序遍

前言


Java关于ACM的代码真的好少,想参考如何用java实现二叉树google了一上午都没找到资料,只能自己仿照之前写的c代码,实现一遍,供大家吐槽参考


题目


根据二叉树前序遍历序列例如:7,-7,8,#,#,-3,6,#,9,#,#,#,-5,#,#,构建二叉树,并且用前序、中序、后序进行遍历


代码


import java.util.Scanner;


public class BinaryTree {
public static String[] str;
public static int count;


/**
* 静态内部类,定义二叉树节点
*/
static class TreeNode {
public String data;
TreeNode lchild;
TreeNode rchild;


public TreeNode(String x) {
this.data = x;
}
}


/**
* 根据前序序列递归构建二叉树
*
* @return
*/
public static TreeNode createBtree() {
TreeNode root = null;


if (count >= str.length || str[count++].equals("#")) {
root = null;
} else {
root = new TreeNode(str[count - 1]);
root.lchild = createBtree();
root.rchild = createBtree();
}


return root;
}


/**
* 前序遍历
*
* @param root
*/
public static void preTraverse(TreeNode root) {
if (root != null) {
System.out.print(root.data + " ");
preTraverse(root.lchild);
preTraverse(root.rchild);
}
}


/**
* 中序遍历
*
* @param root
*/
public static void inTraverse(TreeNode root) {
if (root != null) {
inTraverse(root.lchild);
System.out.print(root.data + " ");
inTraverse(root.rchild);
}
}


/**
* 后序遍历
*
* @param root
*/
public static void postTraverse(TreeNode root) {
if (root != null) {
postTraverse(root.lchild);
postTraverse(root.rchild);
System.out.print(root.data + " ");
}
}


public static void main(String args[]) {
Scanner cin = new Scanner(System.in);


while (cin.hasNext()) {
String s = cin.nextLine();
str = s.split(",");


count = 0;


TreeNode root = createBtree();


// 前序遍历
preTraverse(root);
System.out.println();


// 中序遍历
inTraverse(root);
System.out.println();


// 后序遍历
postTraverse(root);
System.out.println();
}
}
}


相关阅读:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android从图库(Gallery)选择一张.. 下一篇C语言共用体union的用法举例

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: