java建立二叉树,递归/非递归先序遍历,递归/非递归中序遍历,层次遍历

import java.util.LinkedList;
import java.util.Scanner;
import java.util.Stack;

//structure of binary tree
class BiTree {
	BiTree lchild;
	BiTree rchild;
	String data;
}

public class BiTreeTest {
	static Scanner scanner = new Scanner(System.in);

	// test case: a b c # # d e # g # # f # # #
	static BiTree createBiTree(BiTree root) {
		String data = scanner.next();
		if (data.equals("#")) {
			return null;
		} else {
			root = new BiTree();
			root.data = data;
			root.lchild = createBiTree(root.lchild);
			root.rchild = createBiTree(root.rchild);
			return root;
		}
	}

	// preOrder recursive traverse
	static void preOrderRecur(BiTree root) {
		if (root != null) {
			System.out.print(root.data + " ");
			preOrderRecur(root.lchild);
			preOrderRecur(root.rchild);
		}
	}

	// inOrder recursive traverse
	static void inOrderRecur(BiTree root) {
		if (root != null) {
			inOrderRecur(root.lchild);
			System.out.print(root.data + " ");
			inOrderRecur(root.rchild);
		}
	}

	// preOrder in non-recursive
	static void preOrder(BiTree root) {
		Stack<BiTree> stack = new Stack<BiTree>();
		BiTree cur;
		stack.push(root);
		while (!stack.empty()) {
			while ((cur = stack.peek()) != null) {
				System.out.print(cur.data + " ");
				stack.push(cur.lchild);
			}
			cur = stack.pop();
			if (!stack.empty() && (cur = stack.pop()) != null) {
				stack.push(cur.rchild);
			}
		}
	}

	// inOrder in non-recursive
	static void inOrder(BiTree root) {
		Stack<BiTree> stack = new Stack<BiTree>();
		BiTree cur;
		stack.push(root);
		while (!stack.empty()) {
			while ((cur = stack.peek()) != null) {
				stack.push(cur.lchild);
			}
			stack.pop();
			if (!stack.empty() && (cur = stack.pop()) != null) {
				System.out.print(cur.data + " ");
				stack.push(cur.rchild);
			}
		}
	}

	// level traverse,use LinkedList instead of queue data structure
	static void levelTraverse(BiTree root) {
		LinkedList<BiTree> list = new LinkedList<BiTree>();
		BiTree cur;
		list.add(root);
		while (list.size() != 0) {
			cur = list.removeFirst();
			if (cur != null) {
				System.out.print(cur.data + " ");
			}
			if (cur.lchild != null) {
				list.add(cur.lchild);
			}
			if (cur.rchild != null) {
				list.add(cur.rchild);
			}
		}
	}

	public static void main(String[] args) {
		BiTree root = null;
		root = createBiTree(root);
		// preOrderRecur(root);
		// inOrderRecur(root);
		// inOrder(root);
		levelTraverse(root);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值