import java.util.*;
public class BinaryTree {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode() {
}
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static TreeNode createTree() {
Scanner sc = new Scanner(System.in);
System.out.println("数组长度:");
int length = sc.nextInt();
//-1代表null
System.out.println("数组值:");
int[] arr = new int[length];
for (int i = 0; i < length; i++) {
arr[i] = sc.nextInt();
}
List<TreeNode> list = new ArrayList<>();
for (int i : arr) {
TreeNode node = null;
if (i != -1) {
node = new TreeNode(i);
}
list.add(node);
}
for (int i = 0; 2 * i + 2 < list.size(); i++) {
if (list.get(i) != null) {
list.get(i).left = list.get(2 * i + 1);
list.get(i).right = list.get(2 * i + 2);
}
}
//可以只生成奇数个节点,使得最后一个父节点必定存在右子节点,那么下面的处理可以省略
int lastFather = (list.size() - 1 - 1) / 2;
if (list.size() % 2 == 0) {
list.get(lastFather).left = list.get(list.size() - 1);
}
return list.get(0);
}
public static void traverse(TreeNode root) {
if (root == null) {
return;
}
Deque<TreeNode> stack = new LinkedList<>();
TreeNode cur = root;
while (!stack.isEmpty() || cur != null) {
if (cur != null) {
stack.push(cur);
cur = cur.left;
} else {
cur = stack.pop();
System.out.print(cur.val+"\t");
cur = cur.right;
}
}
}
public static void main(String[] args) {
traverse(createTree());
}
}
利用数组生成二叉树
最新推荐文章于 2024-05-14 18:27:26 发布