[leetcode-297]Serialize and Deserialize Binary Tree(java)

问题描述:这里写链接内容
这道题思路毕竟简单,就是定义一套规则,一套序列化成字符串,然后再反序列化的规则。
我的思路很简单:序列化过程中,采用广搜的思路,在对每一层而言,如果该节点为null,那么在字符串中添加一个‘#’,如果不为null,就添加一个该数,其中每个节点都以,为分割。
反序列化时,首先调用split函数,将字符串解析成字符串数组,然后对数组进行遍历,获取每个数组元素,如果为“#”时,将null添加到树中,否则从一个队列中取出父节点,因为对于非叶节点而言,每个节点有两个子元素(包括null),但是对于null节点而言,没有任何子元素。
【[leetcode-297]Serialize and Deserialize Binary Tree(java)】代码如下:

/** * Definition for a binary tree node. * public class TreeNode { *int val; *TreeNode left; *TreeNode right; *TreeNode(int x) { val = x; } * } */ public class Codec { //tools for reconstruct treenode Queue queue = new LinkedList(); boolean isLeft = true; TreeNode root = null; // Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuilder builder = new StringBuilder(); Queue queue = new LinkedList<>(); queue.offer(root); while(!queue.isEmpty()){ TreeNode top = queue.poll(); if(top == null){ builder.append('#'); builder.append(','); } else{ builder.append(top.val); builder.append(','); //以,作为分割 queue.offer(top.left); queue.offer(top.right); } } return builder.toString(); }// Decodes your encoded data to tree. public TreeNode deserialize(String data) { String[] strs = data.split(","); int size = strs.length; for(int i = 0; iif(curstr.length() == 0) continue; else if(curstr.equals("#")){ appendNodeToTree(null); }else{ int val = Integer.parseInt(curstr); appendNodeToTree(new TreeNode(val)); } } return root; } private void appendNodeToTree(TreeNode node){ if(root == null){ root = node; queue.offer(node); return; } TreeNode top = queue.peek(); if(isLeft){ top.left = node; }else{ top.right = node; queue.poll(); } isLeft = !isLeft; //取反 if(node != null) queue.offer(node); } }// Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root));

    推荐阅读