N叉树如何通过二叉树来序列化、并完成反序列化

解题思路

多叉树转二叉树是要思考,如何将多叉树的每个节点都转到二叉树的节点上,且不会产生歧义,就是每个节点都能一眼看出他原本的位置.
方法:子节点的第一节点放在头节点的左节点上没然后依次放在右节点上.画个图帮助理解.
在这里插入图片描述
2 3 4 三个节点是1 这个节点的子节点,第一个子节点2 放在1 的左节点,剩下的依次都放右节点, 2 3 4的子节点也是这个规则 依次放下去.

多叉树和二叉树的代码定义

  /**
     * 多叉树
     */
    public class Node{
        public int val;
        public List<Node> children;

        public Node(int val) {
            this.val = val;
        }

        public Node(int val, List<Node> children) {
            this.val = val;
            this.children = children;
        }
    }


    /**
     * 二叉树
     */
    public class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

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

序列化

 public static TreeNode encode(Node node){
        if (null == node){
            return null;
        }
        TreeNode head = new TreeNode(node.val);
        head.left = en(node.children);
        return head;
    }

    public static TreeNode en(List<Node>children){
        if (null == children || children.size() == 0){
            return null;
        }
        TreeNode cur = null;
        TreeNode left = null;
        for (Node child : children){
            TreeNode treeNode = new TreeNode(child.val);
            if (left == null){
                left = treeNode;
            }else{
                cur.right = treeNode;
            }
            cur = treeNode;
            cur.left = en(child.children);
        }
        return left;
    }

反序列化

 public static Node decode(TreeNode head){
        if (null == head){
            return null;
        }
        return new Node(head.val,de(head.left));
    }

    public static List<Node> de(TreeNode left){
        ArrayList<Node> nodes = new ArrayList<>();
        while (left != null){
            Node cur = new Node(left.val,de(left.left));
            nodes.add(cur);
            left = left.right;
        }
        return nodes;
    }

leetcode 原题链接

leetcode原题链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值