反序列化二叉树

12 篇文章 0 订阅
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);

        }
    }

}

}







主要是用的层序遍历和先序遍历构建二叉树

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值