把一个数组的值存入二叉树中,然后利用前序、中序、后序3种方式进行遍历(完整代码以及运行结果)
在最近的面试过程中,听说有小伙伴被面试官要求创建二叉树,然后对该二叉树进行遍历,感觉这一直以来都是一个大家不太注意的点,因为大家平时刷算法题,都是在leetcode或者牛客网上刷的,都是直接写关键代码,对于如何去创建一个二叉树,然后将数组中的值导入进去,一直以来是难题,故今天来记录一下,如何创建一个二叉树,然后利用该二叉树去遍历或者做一些其他的操作。
代码如下:
package TreeNode;
import java.util.LinkedList;
import java.util.List;
public class BinaryTree {
private int[] array = {1,2,3,5,6,7,8,9,10};
private static List<Node> nodeList = null;
private static class Node{
int Val;
Node left;
Node right;
Node(int newVal){
left = null;
right = null;
Val = newVal;
}
}
public void creatBinTree(){
nodeList = new LinkedList<Node>();
for(int nodeIndex = 0; nodeIndex < array.length; nodeIndex++){
nodeList.add(new Node(array[nodeIndex]));
}
for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++){
nodeList.get(parentIndex).left = nodeList.get(parentIndex * 2 + 1);
nodeList.get(parentIndex).right = nodeList.get(parentIndex * 2 + 2);
}
int lastParentIndex = array.length / 2 - 1;
nodeList.get(lastParentIndex).left = nodeList.get(lastParentIndex * 2 + 1);
if(array.length % 2 == 1){
nodeList.get(lastParentIndex).right = nodeList.get(lastParentIndex * 2 + 2);
}
}
//前序遍历
public static void preOrder(Node node){
if(node == null){
return;
}
System.out.print(node.Val + " ");
preOrder(node.left);
preOrder(node.right);
}
//中序遍历
public static void inOrder(Node node){
if(node == null){
return;
}
inOrder(node.left);
System.out.print(node.Val + " ");
inOrder(node.right);
}
//后序遍历
public static void postOrder(Node node){
if(node == null){
return;
}
postOrder(node.left);
postOrder(node.right);
System.out.print(node.Val + " ");
}
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
binaryTree.creatBinTree();
//nodeList中第0个索引处的值为根节点
Node root = nodeList.get(0);
System.out.println("先序遍历:");
preOrder(root);
System.out.println();
System.out.println("中序遍历:");
inOrder(root);
System.out.println();
System.out.println("后序遍历:");
postOrder(root);
//System.out.println();
}
}
输出结果:
先序遍历:
1 2 5 9 10 6 3 7 8
中序遍历:
9 5 10 2 6 1 7 3 8
后序遍历:
9 10 5 6 2 7 8 3 1