树的遍历-先序遍历、中序遍历、后序遍历
先序遍历
二叉树的先序遍历,就是先输出根结点,再遍历左子树,最后遍历右子树,遍历左子树和右子树的时候,同样遵循先序遍历的规则。
public void preOrder(TreeNode treeNode){
if(treeNode == null){
return;
}
System.out.print(" " + treeNode.value);
preOrder(treeNode.left);
preOrder(treeNode.right);
}
中序遍历
二叉树的中序遍历,就是先递归中序遍历左子树,再输出根结点的值,再递归中序遍历右子树。
public void inOrder(TreeNode treeNode){
if(treeNode == null){
return;
}
inOrder(treeNode.left);
System.out.print(" " + treeNode.value);
inOrder(treeNode.right);
}
后序遍历
二叉树的后序遍历,就是先递归后序遍历左子树,再递归后序遍历右子树,最后输出根结点的值。
public void postOrder(TreeNode treeNode){
if(treeNode == null){
return;
}
postOrder(treeNode.left);
postOrder(treeNode.right);
System.out.print(" " + treeNode.value);
}
案例:
public class TreeDemo {
public class TreeNode{
private Integer value;
private TreeNode right;
private TreeNode left;
public TreeNode() {
}
public TreeNode(Integer value, TreeNode left, TreeNode right) {
this.value = value;
this.right = right;
this.left = left;
}
public Integer getvalue() {
return value;
}
public void setvalue(Integer value) {
this.value = value;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
}
public static void main(String[] args) {
TreeDemo treeDemo = new TreeDemo();
TreeNode tree = treeDemo.getTree();
System.out.println("先序遍历:");
treeDemo.preOrder(tree);
System.out.println();
System.out.println("中序遍历:");
treeDemo.inOrder(tree);
System.out.println();
System.out.println("后序遍历:");
treeDemo.postOrder(tree);
}
public TreeNode getTree(){
TreeNode treeNode = new TreeNode();
treeNode.setvalue(13);
treeNode.setLeft(new TreeNode(10,
new TreeNode(7,
new TreeNode(3,null,null),new TreeNode(4,null,null)),
new TreeNode(12,new TreeNode(11,null,null),null)));
treeNode.setRight(new TreeNode(15,
new TreeNode(14,null,null),
new TreeNode(17,null,null)));
return treeNode;
}
public void preOrder(TreeNode treeNode){
if(treeNode == null){
return;
}
System.out.print(" " + treeNode.value);
preOrder(treeNode.left);
preOrder(treeNode.right);
}
public void inOrder(TreeNode treeNode){
if(treeNode == null){
return;
}
inOrder(treeNode.left);
System.out.print(" " + treeNode.value);
inOrder(treeNode.right);
}
public void postOrder(TreeNode treeNode){
if(treeNode == null){
return;
}
postOrder(treeNode.left);
postOrder(treeNode.right);
System.out.print(" " + treeNode.value);
}
}
结果如下:
|