二叉树的遍历:前序遍历,中序遍历,后序遍历,层次遍历
如何进行前序遍历:
1、 先遍历树根
2、 然后前序遍历左子树
3、 再前序遍历右子树
如何进行中序遍历:
1、 先中序遍历左子树
2、 然后遍历树根
3、 再中序遍历右子树
如何进行后序遍历:
1、 先后序遍历左子树
2、 然后后序遍历右子树
3、 再遍历树根
前序:ABDEGCF
中序:DBGEACF
后序:DGEBFCA
代码示例:
package com.sise.recursion;
/*
* 遍历
*/
public class TreeTraversal {
/*
* 前序遍历
*/
public void preOrder(TreeNode root) {
if(root==null){
return;
}
System.out.print(root.getValue());
preOrder(root.getLeft());
preOrder(root.getRighe());
}
/*
* 中序遍历
*/
public void inOrder(TreeNode root) {
if(root==null){
return;
}
inOrder(root.getLeft());
System.out.print(root.getValue());
inOrder(root.getRighe());
}
/*
* 后序遍历
*/
public void postOrder(TreeNode root) {
if(root==null){
return;
}
postOrder(root.getLeft());
postOrder(root.getRighe());
System.out.print(root.getValue());
}
public static void main(String[] args) {
TreeCreator creator=new TreeCreator();
TreeTraversal traversal=new TreeTraversal();
TreeNode sampleTree=creator.createSampleTree();
System.out.print("前序:");
traversal.preOrder(sampleTree);
System.out.println();
System.out.print("中序:");
traversal.inOrder(sampleTree);
System.out.println();
System.out.print("后序:");
traversal.postOrder(sampleTree);
System.out.println();
}
}
package com.sise.recursion;
/*
* 建树
*/
public class TreeCreator {
public TreeNode createSampleTree() {
TreeNode root=new TreeNode('A');
root.setLeft(new TreeNode('B'));
root.getLeft().setLeft(new TreeNode('D'));
root.getLeft().setRighe(new TreeNode('E'));
root.getLeft().getRighe().setLeft(new TreeNode('G'));
root.setRighe(new TreeNode('C'));
root.getRighe().setRighe(new TreeNode('F'));
return root;
}
}
package com.sise.recursion;
public class TreeNode {
private final char value;
private TreeNode left;
private TreeNode righe;
public TreeNode (char value) {
this.value=value;
this.left=null;
this.righe=null;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRighe() {
return righe;
}
public void setRighe(TreeNode righe) {
this.righe = righe;
}
public char getValue() {
return value;
}
}
运行结果: