二叉树的遍历分为中序,前序,后序;就是利用函数递归来实现的遍历,没啥好说的,直接上代码:
class TreeNode {
int value;
TreeNode left_node;
TreeNode right_node;
public TreeNode(int value) {
this.value = value;
this.left_node = null;
this.right_node = null;
}
}
public class BinaryTree {
public TreeNode rootNode;
public void Add_Node_To_Tree(int value) {
if(rootNode == null) {
rootNode = new TreeNode(value);
return;
}
TreeNode currentNode = rootNode;
while (true) {
if(value < currentNode.value) {
if(currentNode.left_node == null) {
currentNode.left_node = new TreeNode(value);
return;
}
else {
currentNode = currentNode.left_node;
}
}
else {
if(currentNode.right_node == null) {
currentNode.right_node = new TreeNode(value);
return;
}
else {
currentNode = currentNode.right_node;
}
}
}
}
//中序遍历
public void InOrder(TreeNode node) {
if(node != null) {
InOrder(node.left_node);
System.out.println("[" + node.value + "]");
InOrder(node.right_node);
}
}
//前序遍历
public void PreOrder(TreeNode node) {
if(node != null) {
System.out.println("[" + node.value + "]");
PreOrder(node.left_node);
PreOrder(node.right_node);
}
}
//后序遍历
public void PostOrder(TreeNode node) {
if(node != null) {
PostOrder(node.left_node);
PostOrder(node.right_node);
System.out.println("[" + node.value + "]");
}
}
public static void main(String[] args) throws IOException {
int i;
int arr[] = {7, 4, 1, 5, 16, 8, 11, 12, 15, 9, 2};
BinaryTree tree = new BinaryTree();
System.out.println("原始内容:\n");
for(i=0;i<11;i++) {
System.out.println("[" + arr[i] + "]");
}
System.out.println();
for (i=0;i<arr.length;i++) {
tree.Add_Node_To_Tree(arr[i]);
}
System.out.println("二叉树内容:\n");
System.out.println("前序遍历结果:\n");
tree.PreOrder(tree.rootNode);
System.out.println();
System.out.println("中序遍历结果:\n");
tree.InOrder(tree.rootNode);
System.out.println();
System.out.println("后序遍历结果:\n");
tree.PostOrder(tree.rootNode);
System.out.println();
}
}
运行结果截图: