定义结构体
public class Node {
int value;
Node left;
Node right;
public Node(int value, Node left, Node right) {
this.value = value;
this.left = left;
this.right = right;
}
}
/**
* 二叉树结构:
* 1
* / \
* 2 3
* / / \
* 4 5 6
* \ /
* 7 8
*/
构建二叉树并递归进行前序、中序、后序遍历
注意:构建二叉树时,是由下往上构建的,即先构建子节点,再构建父节点。
public class binaryTree {
public static Node initTree(){
Node n7 = new Node(7,null,null);
Node n8 = new Node(8,null,null);
Node n4 = new Node(4,null,n7);
Node n5 = new Node(5,null,null);
Node n6 = new Node(6,n8,null);
Node n2 = new Node(2,n4,null);
Node n3 = new Node(3,n5,n6);
Node n1 = new Node(1,n2,n3);
return n1;
}
//前序遍历
public static void preOrderRecur(Node head){
if(head == null){
return;
}
System.out.print(head.value+" ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
//中序遍历
public static void inOrderRecur(Node head){
if(head==null){
return;
}else{
inOrderRecur(head.left);
System.out.print(head.value+" ");
inOrderRecur(head.right);
}
}
//后序遍历
public static void postOrderRecur(Node head){
if (head == null){
return;
}else{
postOrderRecur(head.left);
postOrderRecur(head.right);
System.out.print(head.value+" ");
}
}
public static void main(String[] args) {
Node node = binaryTree.initTree();
System.out.print("先序遍历:");
binaryTree.preOrderRecur(node);
System.out.println();
System.out.print("中序遍历:");
binaryTree.inOrderRecur(node);
System.out.println();
System.out.print("后序遍历:");
binaryTree.postOrderRecur(node);
}
}
/**
*先序遍历:1 2 4 7 3 5 6 8
*中序遍历:4 7 2 1 5 3 8 6
*后序遍历:7 4 2 5 8 6 3 1
*/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)