package 二叉树的遍历;
public class BinaryTree {
//根节点
TreeNode root;
//设置根节点
public void setRoot(TreeNode root) {
this.root = root;
}
public TreeNode getRoot() {
return root;
}
//前序
public void frontShow()
{
root.frontShow();
}
//中序
public void midShow()
{
root.midShow();
}
//后序
public void afterShow()
{
root.afterShow();
}
public static void main(String[] args) {
//创建一棵树
BinaryTree bt=new BinaryTree();
//创建一个根节点
TreeNode root=new TreeNode(1);
//把根节点赋给树
bt.setRoot(root);
//创建两个节点
TreeNode rootL=new TreeNode(2);
TreeNode rootR=new TreeNode(3);
//把新创建的节点设置为根节点的子节点
root.setleftNode(rootL);
root.setrightNode(rootR);
//为第二层的节点创建子节点
rootL.setleftNode(new TreeNode(4));
rootL.setrightNode(new TreeNode(5));
rootR.setleftNode(new TreeNode(6));
rootR.setrightNode(new TreeNode(7));
//遍历二叉树
//1.前序遍历(根,左,右)
System.out.println("此二叉树的前序遍历为:");
bt.frontShow();
System.out.println();
System.out.println("此二叉树的中序遍历为:");
bt.midShow();
System.out.println();
System.out.println("此二叉树的后序遍历为:");
bt.afterShow();
}
}
class TreeNode
{
//节点的权
int value;
//左孩子
TreeNode leftNode;
//右孩子
TreeNode rightNode;
public TreeNode(int value)
{
this.value=value;
}
//前序遍历(根,左,右)
public void frontShow() {
//先遍历当前节点(根节点);
System.out.print(value);
//左节点
if(leftNode!=null)
{
leftNode.frontShow();
}
//右节点
if(rightNode!=null)
{
rightNode.frontShow();
}
}
//中序遍历(左,根,右)
public void midShow() {
//先遍历左节点
if(leftNode!=null)
{
leftNode.midShow();
}
//在遍历当前节点(根节点);
System.out.print(value);
//最后右节点
if(rightNode!=null)
{
rightNode.midShow();
}
}
//后序遍历(左,右,根)
public void afterShow() {
//先左节点
if(leftNode!=null)
{
leftNode.afterShow();
}
//在右节点
if(rightNode!=null)
{
rightNode.afterShow();
}
//最后遍历当前节点(根节点);
System.out.print(value);
}
//设置左孩子
public void setleftNode(TreeNode lNode) {
this.leftNode = lNode;
}
//设置右孩子
public void setrightNode(TreeNode rNode) {
this.rightNode = rNode;
}
}