序列化二叉桑(hard)
题解
-
递归
- 剑指 offer解法(我不会)
-
层序遍历
- 算法思想
- 序列化
- 利用层次比遍历将二叉树的节点记录到数组中(包括 null)
- 复杂度分析
- 时间复杂度O(n):N 为二叉树的节点数,层序遍历需要访问所有节点,最差情况下需要访问 N + 1 个 null ,总体复杂度为 O(2N + 1) = O(N) 。
- 空间复杂度O(n): 最差情况下,队列 queuequeue 同时存储 (n+1)/2个节点(或 N+1 个null ),使用 O(N);列表 res 使用 O(N) 。
- 复杂度分析
- 利用层次比遍历将二叉树的节点记录到数组中(包括 null)
- 反序列化
- 传入节点记录数组
- 利用队列保存已经构建的节点,以便添加其子节点。
- 当某一节点的左右子节点都添加后,或者没有左右子节点,则出队。
- 复杂度分析
- 时间复杂度 O(n):n 为二叉树节点数,层次构建二叉树需要遍历整个 vals,长度最大为 2n+1
- 空间复杂度 O(n):最差情况下queue 同时存储 (n+1)/2个节点
- 复杂度分析
- 序列化
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode le * TreeNode(int x) { val = x; } * } */ public class Codec { // Encodes a tree to a single string. public String serialize(TreeNode root) { if(root == null)return "[]"; StringBuilder sb = new StringBuilder(); sb.append("["); Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while(!queue.isEmpty()){ TreeNode node = queue.poll(); if(node != null){ sb.append(node.val + ","); queue.add(node.left); queue.add(node.right); }else{ sb.append("null,"); } } return sb.substring(0,sb.length()-1) + "]"; } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if(data.equals("[]"))return null; String vals[] = data.substring(1,data.length()-1).split(","); TreeNode root = new TreeNode(Integer.parseInt(vals[0])); Queue<TreeNode> queue = new LinkedList<>(){{ add(root);}}; int i = 1; while(!queue.isEmpty()){ TreeNode node = queue.poll(); //反序列过程中,空节点不加入队列,这是因为加入队列的原因是为了保存节点, //以便添加其子节点,vals 中没有 null 的子节点,则 null 自然不用加入队列 if(!vals[i].equals("null")){ node.left = new TreeNode(Integer.parseInt(vals[i])); queue.add(node.left); } i++; if(!vals[i].equals("null")){ node.right = new TreeNode(Integer.parseInt(vals[i])); queue.add(node.right); } i++; } return root; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root));
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-POmub4GY-1596773800951)(/Users/apple/Library/Application Support/typora-user-images/image-20200807120722384.png)]
- 算法思想
总结
- 关于递归如何更好地回传值需要学习一下
- 反序列过程中,空节点不加入队列,这是因为加入队列的原因是为了保存节点,以便添加其子节点,vals 中没有 null 的子节点,则 null 自然不用加入队列