package tree;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author zhao
* @version 1.0
* @date 2023/9/4 16:31
* 二叉树
*/
public class BinaryTree {
public static void main(String[] args) {
Integer[] arr = new Integer[]{1, null, 4, 8, 2, null, null, 3, 6};
long begin = System.currentTimeMillis();
CreateBT createBT = new CreateBT();
HeroNode node = createBT.createTree(arr);
long end = System.currentTimeMillis();
//先序遍历
createBT.preOrderTraverse(node);
System.out.println("耗时:" + (end - begin) + "ms");
}
}
//构建二叉树
class CreateBT {
public HeroNode createTree(Integer[] arr) {
if (arr.length == 0) {
return null;
}
HeroNode root = new HeroNode(arr[0]);
//根结点就是右子树,不断轮换
Queue<HeroNode> queue = new LinkedList<>();
queue.add(root);
boolean isLeft = true;//是左子树
for (int i = 1; i < arr.length; i++) {
HeroNode node = queue.peek(); //peek()获取对头元素
//左子树
if (isLeft) {
if (arr[i] != null) {
node.left = new HeroNode(arr[i]);
queue.offer(node.left); //offer(E e) 在队列尾部添加一个元素,并返回是否成功
}
isLeft = false;
//右子树
} else {
if (arr[i] != null) {
node.right = new HeroNode(arr[i]);
queue.offer(node.right);
}
//右节点加入队列尾部,删除第一个元素,保证队列里保存的是根节点
queue.poll(); //poll() 删除队列中第一个元素,并返回该元素的值,
isLeft = true;
}
}
return root;
}
//前序遍历二叉树(根左右)
public static void preOrderTraverse(HeroNode node) {
if (node == null) {
return;
}
System.out.print(node.age + " ");
preOrderTraverse(node.left);
preOrderTraverse(node.right);
}
}
//定义结点信息
class HeroNode {
public Integer age;
public HeroNode left; //默认为空
public HeroNode right;
public HeroNode() {
}
public HeroNode(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "HeroNode{" +
"age=" + age +
", left=" + left +
", right=" + right +
'}';
}
}