Java Solution


  • 0
    S

    '''/**

    • Definition for a binary tree node.

    • public class TreeNode {

    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      public class Codec {
      final char noLeft = 'L';
      final char noRight = 'R';
      final char noChild = 'N';
      final String delim = ":";
      // Encodes a tree to a single string.
      public String serialize(TreeNode root) {
      StringBuilder sb = new StringBuilder();
      serialize(sb, root);
      if(sb.length()==0){
      return "";
      }
      return sb.substring(1);
      }
      public void serialize(StringBuilder sb, TreeNode root){
      if(root == null){
      return;
      }
      sb.append(delim+root.val);
      if(root.left==null&&root.right==null){
      sb.append(noChild);
      }
      else if(root.left==null){
      sb.append(noLeft);
      }
      else if(root.right==null){
      sb.append(noRight);
      }
      serialize(sb, root.left);
      serialize(sb, root.right);
      }

      // Decodes your encoded data to tree.
      public TreeNode deserialize(String data) {
      String[] split = data.split(delim);
      if(split.length==0){
      return null;
      }
      Queue<String> queue = new LinkedList<>();
      for(int i =0; i<split.length; i++){
      queue.add(split[i]);
      }
      return deserialize(queue);
      }

      public TreeNode deserialize(Queue<String> queue){
      if(queue.isEmpty()){
      return null;
      }
      String curData = queue.poll();
      if(curData==null||curData.length()==0){
      return null;
      }
      char last = curData.charAt(curData.length()-1);
      if(last==noLeft||last==noRight||last==noChild){
      curData = curData.substring(0, curData.length()-1);
      }
      TreeNode node = new TreeNode(Integer.parseInt(curData));
      if(last==noLeft){
      node.right = deserialize(queue);
      }
      else if(last==noRight){
      node.left = deserialize(queue);
      }
      else if(last!=noChild){
      node.left = deserialize(queue);
      node.right = deserialize(queue);
      }
      return node;
      }
      }
      // Your Codec object will be instantiated and called as such:
      // Codec codec = new Codec();
      // codec.deserialize(codec.serialize(root));


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.