数据结构--二叉树遍历前序、中序、后序(java实现)

转载:http://blog.csdn.net/wzy_1988/article/details/16943473


package com.text.tool;

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();
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值