继上次说的二叉树的构造之后,再给大家说下二叉树的遍历
4种遍历
- 前序遍历:(根->左->右)
- 中序遍历:(左->根->右)
- 后续遍历:(左->右->根)
- 广度遍历:(依照层级,然后自左向右)
额…什么?解释的不够清楚,没关系,后面代码的具体实现,你一看便知。
针对上面的二叉树,不同的遍历参数的结果不同,但结点都是全部被访问到,并且是只被访问到一次。
1. 前序遍历:apobc
2. 中序遍历:opacb
3. 后续遍历:opcba
4. 广度遍历:apboc
具体实现:
public class Test {
public static void main(String[] args) throws Exception {
//必须是扩展二叉树的格式的前序遍历
TwoXTree tree=new TwoXTree(new Object[]{
"a","p","o",'#','#','#',"b",'c','#','#','#'});
//前序遍历
tree.printThreeXNode1(tree.getFrist());
//中序遍历
tree.printThreeXNode2(tree.getFrist());
//后续遍历
tree.printThreeXNode3(tree.getFrist());
//广度遍历
tree.printThreeXNode4(tree.getFrist());
}
}
/**
* 三叉链表
* @author name:zf Email:[email protected]
*/
class ThreeXChainTree{
/**
* 左孩子
*/
private ThreeXChainTree left;
/**
* 右孩子
*/
private Thr