序列化二叉树
序列化二叉树
http://www.nowcoder.com/questionTerminal/cf7e25aa97c04cc1a68c8f040e71fb84
序列化二叉树:
层次遍历的改进,定义一个数值sum用来存储当前队列中不为空值的个数。
public static String Serialize(TreeNode root) { String result = ""; if(root == null) { result = "null"; return result; } StringBuffer str = new StringBuffer(); Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int sum = 1; //用来记录队列中当前不为空的个数 while(sum!=0){ TreeNode t = queue.poll(); if(t == null ){ str.append("null"); }else{ if(t.left!=null) { sum++; } if(t.right!=null) { sum++; } queue.add(t.left); queue.add(t.right); str.appe***al); sum--; } if(sum > 0) str.append(","); } result = str.toString(); return result; }
反序列化二叉树
定义一个数组treeNodes用来存放val值等于序列中的值TreeNode节点。
TreeNode Deserialize(String str) { TreeNode head = null; if(str == null || str.length() == 0) return head; String[] nodes = str.split(","); TreeNode[] treeNodes = new TreeNode[nodes.length]; for(int i=0; i<nodes.length; i++){ if(!nodes[i].equals("null")) treeNodes[i] = new TreeNode(Integer.valueOf(nodes[i])); } for(int i=0, j=1; j<treeNodes.length; i++){ if(treeNodes[i] != null){ treeNodes[i].left = treeNodes[j++]; if(j<treeNodes.length) treeNodes[i].right = treeNodes[j++]; } } return treeNodes[0]; }