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<String> tree = new ThreeLinkBinTree<String>("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 <E> List<Node> brFirSear(ThreeLinkBinTree<E> tree){
return brFirSear(tree.root());
}
private static <E> List<Node> brFirSear(ThreeLinkBinTree<E>.Node root) {
List<Node> nodes = new ArrayList<Node>();
Deque<Node> deque = new ArrayDeque<Node>();
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]