直接上代码
/*
二叉树的构建
*/
class TreeNode {
TreeNode right;
TreeNode left;
int val;
public TreeNode(int val) {
this.val = val;
}
}
/*
前序遍历
先输出根节点
在遍历左子树
后遍历右子树
*/
public void prorder(TreeNode head) {
if (head == null) {
return;
}
System.out.print(head.val + "\t");
if (head.left != null) {
prorder(head.left);
}
if (head.right != null) {
prorder(head.right);
}
}
/*
后序遍历
先遍历左子树
再遍历右子树
最后输出根节点
*/
public void epilogue(TreeNode head) {
if (head == null) {
return;
}
if (head.left != null) {
epilogue(head.left);
}
if (head.right != null) {
epilogue(head.right);
}
System.out.print(head.val + "\t");
}
/*
中序遍历
先遍历左子树
再输出根节点
后遍历右子树
*/
public void Infix(TreeNode head) {
if (head == null) {
return;
}
if (head.left != null) {
Infix(head.left);
}
System.out.print(head.val + "\t");
if (head.right != null) {
Infix(head.right);
}
}