1.基本定义
*二叉树的定义
class BinaryTreeNode {
int val;
BinaryTreeNode left;
BinaryTreeNode right;
public BinaryTreeNode(int no) {
super();
this.val = no;
}
}
*主函数部分
public static void main(String[] args) {
// TODO Auto-generated method stub
BinaryTreeNode root=new BinaryTreeNode(1);
BinaryTreeNode node1=new BinaryTreeNode(5);
BinaryTreeNode node2=new BinaryTreeNode(7);
BinaryTreeNode node3=new BinaryTreeNode(8);
BinaryTreeNode node4=new BinaryTreeNode(10);
root.left=node1;
root.right=node2;
node1.left=node3;
node1.right=node4;
System.out.println("前序遍历:");
preOrder(root);
System.out.println("中序遍历:");
inOrder(root);
System.out.println("后序遍历:");
postOrder(root);
}
2.前序遍历
原则:根 左 右
public static void preOrder(BinaryTreeNode root) {
if(root!=null) {
System.out.println(root.val);
}
if(root.left!=null) {
preOrder(root.left);
}
if(root.right!=null) {
preOrder(root.right);
}
}
3.中序遍历
原则:左 根 右
public static void inOrder(BinaryTreeNode root) {
if(root.left!=null) {
inOrder(root.left);
}
if(root!=null) {
System.out.println(root.val);
}
if(root.right!=null) {
inOrder(root.right);
}
}
4.后序遍历
原则:左 右 根
public static void postOrder(BinaryTreeNode root) {
if(root.left!=null) {
postOrder(root.left);
}
if(root.right!=null) {
postOrder(root.right);
}
System.out.println(root.val);
}
总结:二叉树的三种遍历方法使用的基本方法都是递归的思想