二叉树遍历Java实现

【仅贴代码及测试结果】

-------------------BinaryTree.java------------------------------

class Tree<E>{
E element;
Tree<E> lChild;
Tree<E> rChild;
public Tree(E e){
element = e;
}
}
public class BinaryTree { /**
* 树形如下:
* 1
* / \
* 2 3
* \ / \
* 4 5 6
*/
public static void main(String[] args) { Tree<Integer> n1 = new Tree<Integer>(1);
Tree<Integer> n2 = new Tree<Integer>(2);
Tree<Integer> n3 = new Tree<Integer>(3);
Tree<Integer> n4 = new Tree<Integer>(4);
Tree<Integer> n5 = new Tree<Integer>(5);
Tree<Integer> n6 = new Tree<Integer>(6);
System.out.println("Construct the tree...");
n2.rChild=n4;
n3.lChild=n5;
n3.rChild=n6;
n1.lChild=n2;
n1.rChild=n3; System.out.println("打印先序遍历结果:");
firstOrder(n1);
System.out.println("\n打印中序遍历结果:");
midOrder(n1);
System.out.println("\n打印后序遍历结果:");
lastOrder(n1);
} public static <E> void firstOrder(Tree<E> root){
if(root!=null){
System.out.print(root.element+" ");
firstOrder(root.lChild);
firstOrder(root.rChild);
}
}
public static <E> void lastOrder(Tree<E> root){
if(root!=null){
lastOrder(root.lChild);
lastOrder(root.rChild);
System.out.print(root.element+" ");
}
}
public static <E> void midOrder(Tree<E> root){
if(root!=null){
midOrder(root.lChild);
System.out.print(root.element+" ");
midOrder(root.rChild);
}
} }

输出结果:

Construct the tree...
打印先序遍历结果:
1 2 4 3 5 6
打印中序遍历结果:
2 4 1 5 3 6
打印后序遍历结果:
4 2 5 6 3 1
上一篇:腾讯云域名申请+ssl证书申请+springboot配置https


下一篇:超详细网站博客域名和二级域名、子域名升级HTTPS免费申请SSL证书配置nginx指南