Java基础 - 二叉树的遍历之广度优先遍历

package com.yc.test;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

import com.yc.tree.ThreeLinkBinTree;
import com.yc.tree.ThreeLinkBinTree.Node;

public class BFS {
	/**
	 * 此时二叉树的情况为:
	 * 					           A
	 * 					         │ │
	 * 				             + ←┘ └→ B
	 * 					   │ │	
	 * 				       * ←┘ └→ D
	 * 				     │ │
	 * 				 / ←┘ └→ %
	 * 					   │ │
	 * 				       E ←┘ └→ F
	 * 
	 */
	@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
	public static void main(String[] args) {
		ThreeLinkBinTree tree = new ThreeLinkBinTree("A");
		Node n2_l = tree.addAndReturn(tree.root(), "+", true);
		Node n2_r = tree.addAndReturn(tree.root(), "B", false);

		Node n3_n2_l = tree.addAndReturn(n2_l, "*", true);
		Node n3_n2_r = tree.addAndReturn(n2_l, "D", false);

		Node n4_n3_n2_l = tree.addAndReturn(n3_n2_l, "/", true);
		Node n4_n3_n2_r = tree.addAndReturn(n3_n2_l, "%", false);

		Node n5_n4_n3_n2_l = tree.addAndReturn(n4_n3_n2_r, "E", true);
		Node n5_n4_n3_n2_r = tree.addAndReturn(n4_n3_n2_r, "F", false);

		System.out.println( "广度优先遍历结果为:" + brFirSear(tree) );
	}
	
	public static  List brFirSear(ThreeLinkBinTree tree){
		return brFirSear(tree.root());
	}

	private static  List brFirSear(ThreeLinkBinTree.Node root) {
		List nodes = new ArrayList();
		Deque deque = new ArrayDeque();
		
		deque.offer(root);
		
		while( !deque.isEmpty()){
			Node tempN = deque.poll();
			nodes.add(tempN);
			
			if(tempN.getLeft() != null){
				deque.offer(tempN.getLeft());
			}
			if(tempN.getRight() != null){
				deque.offer(tempN.getRight());
			}
		}
		return nodes;
	}
}


测试结果为:

广度优先遍历结果为:[A, +, B, *, D, /, %, E, F]




你可能感兴趣的:(Java基础)