二叉树的镜像

2014-11-24 08:34:32 · 作者: · 浏览: 1
// 二叉树的结构
class BinaryTreeNode{
	String data;
	BinaryTreeNode left;
	BinaryTreeNode right;
}
/**
 *  输入一个二叉树,输出它的镜像
 */
public class BitreeMirrorImg {
	Scanner scanner = new Scanner(System.in);
	//建立二叉树
	public BinaryTreeNode createTree(BinaryTreeNode root){
		String data;
		data = scanner.next();
		if(data.equals("#")){
			return null;
		}
		root = new BinaryTreeNode();
		root.data = data;
		root.left = createTree(root.left);
		root.right = createTree(root.right);
		return root;
	}
	//得到二叉树的镜像
	public void mirror(BinaryTreeNode root){
		if(root == null){
			return;
		}
		if((root.left == null) && (root.right == null)){
			return;
		}
		BinaryTreeNode temp = root.left;
		root.left = root.right;
		root.right = temp;
		mirror(root.left);
		mirror(root.right);
	}
	//层次遍历二叉树
	public void levelTraverse(BinaryTreeNode root){
		java.util.LinkedList
list= new java.util.LinkedList(); list.add(root); while(list.size() != 0){ BinaryTreeNode node = list.removeFirst(); System.out.print(node.data + " "); if(node.left != null){ list.add(node.left); } if(node.right != null){ list.add(node.right); } } } public static void main(String[] args) { BitreeMirrorImg bmi = new BitreeMirrorImg(); BinaryTreeNode root = null; root = bmi.createTree(root); bmi.mirror(root); bmi.levelTraverse(root); } }