名企面试100题_16

输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。
public static void hierarchyTraverse(BinaryTree tree){
		Queue queue = new Queue();
		
		if(tree.getRoot() != null){
			queue.enQueue(tree.getRoot());
			while(!queue.emptyStack()){
				TreeNode p = queue.deQueue();
				System.out.print(p.getVlaue() + " ");
				if(p.left != null){
					queue.enQueue(p.left);
				}
				if(p.right!=null){
					queue.enQueue(p.right);
				}
			}
			
		}
	}

package cn.emma.interview_15;

import cn.emma.interview_15.BinaryTree.TreeNode;


public class Queue {
	public final static int MAX = 100;
	private static int head;
	private static int tail;
	private static TreeNode[] S = new TreeNode[MAX];
	
	
	public boolean emptyStack(){
		if(head == tail){
			return true;
		}
		return false;
	}
	
	public static void enQueue(TreeNode x){
			S[tail++] = x;
	}
	
	public static TreeNode deQueue(){
		return S[head++];
	}
	
}

你可能感兴趣的:(面试)