import java.util.*;
public class Main{
public static void main(String[] args) {
work1();
//-1 是null
}
//前序遍历
public static void work1()
{
Stack<TreeNode> stack = new Stack<>();
int[] arr = new int[]{1,2,3,4,5,6,7,8,-1};
Stack<Integer> stacki = new Stack<>();
int i=0;
stack.push(new TreeNode(arr[i]));
stacki.push(i);
TreeNode ans = stack.peek();
while (!stacki.isEmpty())
{
while ((i=(i*2+1))<arr.length)
{
stacki.push(i);
stack.peek().left = new TreeNode(arr[i]);
stack.push(stack.peek().left);
}
if(!stacki.isEmpty())
{
i = stacki.pop()*2+2;
if(i<arr.length)
{
TreeNode t = stack.pop().right = arr[i]==-1? null:new TreeNode(arr[i]);
stacki.push(i);
stack.push(t);
}else{
stack.pop();
}
}
}
TreeNode.str(ans);
}
//层序遍历建立二叉树
public static void work2()
{
int[] arr = new int[]{1,2,3,4,5,6,7,8,9,10};
int i=0;
Queue<TreeNode> q = new LinkedList<>();
TreeNode ans = null;
q.offer((ans = new TreeNode(arr[i])));
Queue<Integer> nq = new LinkedList<>();
nq.offer(i);
while (!q.isEmpty())
{
TreeNode cur = q.poll();
i = nq.poll()<<1;
if(i+1<arr.length)
{
cur.left = arr[i]==-1?null: new TreeNode(arr[i+1]);
q.offer(cur.left);
nq.offer(i+1);
}
if(i+2<arr.length)
{
cur.right = arr[i]==-1?null: new TreeNode(arr[i+2]);
q.offer(cur.right);
nq.offer(i+2);
}
}
TreeNode.str(ans);
}
private static class TreeNode
{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
public static void str(TreeNode root)
{
if(root==null)return;
System.out.print(root.val+" ");
str(root.left);
str(root.right);
}
}
}
}
主要是用的层序遍历和先序遍历构建二叉树