本文主要是介绍LCR 156. 序列化与反序列化二叉树,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
w
解题思路:
序列化
反序列化
public class Codec {public String serialize(TreeNode root) {if(root == null) return "[]";StringBuilder res = new StringBuilder("[");Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};while(!queue.isEmpty()) {TreeNode node = queue.poll();//转换研究对象if(node != null) {res.append(node.val + ",");queue.add(node.left);queue.add(node.right);}else res.append("null,");}res.deleteCharAt(res.length() - 1);res.append("]");return res.toString();}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();//转换研究对象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;}
}
这篇关于LCR 156. 序列化与反序列化二叉树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!