先序,中序,后序,层次遍历二叉树

package com.hello;

import java.util.ArrayDeque;
import java.util.Queue;

/*
 * @author 张春蕾  2013年10月8
 */

public class HelloJava{
	public static void main(String[] args){
		Node f = new Node(null,'F',null);
		Node g = new Node(null,'G',null);
		Node e = new Node(null,'E',null);
		Node d = new Node(null,'D',null);
		Node b = new Node(d,'B',e);
		Node c = new Node(f,'C',g);
		Node a = new Node(b,'A',c);
		System.out.print("先序遍历为:");
		getTree1(a);
		System.out.println();
		System.out.print("中序遍历为:");
		getTree2(a);
		System.out.println();
		System.out.print("后序遍历为:");
		getTree3(a);
		System.out.println();
		System.out.println("层次遍历数:");
		getTree4(a);  
	}

	//先序遍历,先跟节点在左子树在右子树
	public static void getTree1(Node a){
		if(a != null){
			System.out.print(a.getCharData());
			if(a.isLeftExist() != false){
				getTree1(a.getLeftChild());
			}
			if(a.isRightExist()!= false){
				getTree1(a.getRightChild());
			}
		}
	}
	//中序遍历,先左子树在根节点最后是右子树
	public static void getTree2(Node a){
		if(a != null){
			if(a.isLeftExist() != false){
				getTree2(a.getLeftChild());
			}
			System.out.print(a.getCharData());
			if(a.isRightExist() != false){
				getTree2(a.getRightChild());
			}

		}
	}
	//后序遍历,先左子树在右子树最后是根节点
	public static void getTree3(Node a){
		if(a != null){
			if(a.isLeftExist() != false){
				getTree3(a.getLeftChild());
			}
			if(a.isRightExist() != false){
				getTree3(a.getRightChild());
			}
			System.out.print(a.getCharData());
		}
	}
	//层次遍历树
	public static void getTree4(Node a){
		Queue<Node> treeQueue = new ArrayDeque<Node>();
	int inputCount = 1;
	int outputCount = 0;
	treeQueue.add(a);
	while(treeQueue.size()>0){
		Node node = treeQueue.remove();
		System.out.print(node.getCharData());
		outputCount++;
		if(node.isLeftExist() != false){
			treeQueue.add(node.getLeftChild());
		}
		if(node.isRightExist() != false){
			treeQueue.add(node.getRightChild());
		}
		if(inputCount == outputCount){
			System.out.println();
			inputCount = treeQueue.size();
			outputCount = 0;
		}
	} 
	}
	}


	class Node{
		private Node leftChild;
		private Node rightChild;
		private char ch;

		public Node(Node leftChild,char ch,Node rightChild){
			this.leftChild = leftChild;
			this.rightChild = rightChild;
			this.ch = ch;
		}

		public char getCharData(){
			return this.ch;
		}
		public Node getLeftChild(){
			return this.leftChild;
		}
		public Node getRightChild(){
			return this.rightChild;
		}

		public boolean isLeftExist(){
			if(this.leftChild == null){
				return false;
			}else{
				return true;
			}
		}

		public boolean isRightExist(){
			if(this.rightChild == null){
				return false;
			}else{
				return true;
			}
		}
	}
先序遍历为:ABDECFG
中序遍历为:DBEAFCG
后序遍历为:DEBFGCA
层次遍历数:
A
BC
DEFG


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值