二叉树遍历

根据如下二叉树,编写java程序。采用三种遍历算法实现,并输出结果


先序遍历
a b e f i c g h 
中序遍历
e b i f a g c h 
后序遍历
e i f b g h c a 

package test;

import java.io.BufferedInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.TreeMap;


public class test {
	static Scanner cin = new Scanner(new BufferedInputStream(System.in));

	private static class Node{
		Node leftchild;
		Node rightchild;
		String data;
		Node(String data,Node leftchild,Node rightchild){
			this.leftchild=leftchild;
			this.rightchild=rightchild;
			this.data= data;
		}
	}
	
	private Node creatBinTree(){
		Node i = new Node("i",null,null);
		Node f = new Node("f",i,null);
		Node e = new Node("e",null,null);
		Node g = new Node("g",null,null);
		Node h = new Node("h",null,null);
		Node b = new Node("b",e,f);
		Node c = new Node("c",g,h);
		Node a = new Node("a",b,c);
		return a;
	}
	
	private void preOrderTraverse(Node node) {
		if(node == null)
			return;
		System.out.print(node.data+" ");
		preOrderTraverse(node.leftchild);
		preOrderTraverse(node.rightchild);
	}
	
	private void postOrderTraverser(Node node) {
		if(node == null)
			return;
		postOrderTraverser(node.leftchild);
		postOrderTraverser(node.rightchild);
		System.out.print(node.data+" ");
		
	}

	private void inOrderTraverser(Node node) {
		if(node == null)
			return;
		inOrderTraverser(node.leftchild);
		System.out.print(node.data+" ");
		inOrderTraverser(node.rightchild);
		
	}
	
	public static void main(String[] args) throws Exception {
		test  tree = new test();
		Node node=tree.creatBinTree();
		//先序遍历
		System.out.println("先序遍历");
		tree.preOrderTraverse(node);
		//中序遍历
		System.out.println("\n中序遍历");
		tree.inOrderTraverser(node);
		//后序遍历
		System.out.println("\n后序遍历");
		tree.postOrderTraverser(node);
	}
	
}



你可能感兴趣的:(二叉树遍历)