WAP二叉树序列化和反序列化

Serialize and deserilize a binary Tree

WAP 线上面试题 livecoding

Design an algorithm to serialize and deserialize a binary tree, in which the tree can be serialized to a list of Integer and this list can be deserilized to the original tree structure.

根据leetcode改编的

并不是leetcode原题,是层序遍历。
一般的是序列化为String,如果是序列化为String,就需要在 node之间插入’!’ 表示结束。
然后’#’表示null。
但本题是list,思想类似,不过处理null有点麻烦.
live coding的时候紧张lol, 面试官都给tips,序列化和反序列化都是层序化,反序列化注意root要先存到queue,按顺序赋给left 和right即可。

代码如下:

package worksExam;
import java.util.*;

class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int val){
        this.val=val;
    }
}

public class Main {

    public List<Integer> serialize(TreeNode root){
        List<Integer> list=new ArrayList<Integer>();
        if(root==null)
            return list;
        LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
        queue.add(root);
        while(queue.isEmpty()==false){
            TreeNode treeNode=queue.peek();
            queue.remove();
            /** -1 表示该节点是null!
             * 如果是表示null,加入null到list,
             * 下面就不要执行了,直接continue到下一次remove。
             * 否则就会进入死循环,所以后面不会有的就continue!
             * */
            if(treeNode.val!=-1){
                list.add(treeNode.val);
            }else{
                list.add(null);
                continue;
            }

            if(treeNode.left!=null){
                queue.add(treeNode.left);
            }
            else{
                queue.add(new TreeNode(-1));
            }
            if(treeNode.right!=null){
                queue.add(treeNode.right);

            }
            else{
                queue.add(new TreeNode(-1));
            }


        }
        return list;
    }




    public TreeNode deserialize(List<Integer> data){
        if(data.size()<1||data==null)
            return null;
        //root
        LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
        TreeNode root=new TreeNode(data.get(0));
        int index=0;
        queue.add(root);
        TreeNode node=null;
        while(!queue.isEmpty()){
            node=queue.remove();
            if(data.get(++index)!=null)
                node.left=new TreeNode(data.get(index));
            if(data.get(++index)!=null)
                node.right=new TreeNode(data.get(index));
            if(node.left!=null){
                queue.add(node.left);
            }
            if(node.right!=null){
                queue.add(node.right);
            }

        }
        return root;
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值