Using PreOrder and Queue in Java


  • 0
    G
    public class Codec {
        
        List<String> serializeList = new LinkedList<String>();
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            getSerializedTree(root);
            String serializedData = "";
            Iterator itr = serializeList.iterator();
            while(itr.hasNext())
            {
                serializedData = serializedData + "," + itr.next();
            }
            
            //System.out.print(serializedData);
            return serializedData;
        }
        
        
        private void getSerializedTree(TreeNode root)
        {
            if(root == null)
                serializeList.add("#");
            else
            {
                serializeList.add(Integer.toString(root.val));
                getSerializedTree(root.left);
                getSerializedTree(root.right);
            }
        }
    
        
        
        
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            Queue<String> desData = new LinkedList<String>();
            TreeNode root;
            String[] dataString = data.split("\\,");
            
            for(int i = 0;i<dataString.length;i++)
            {
                if(dataString[i].length() != 0)
                {
                    desData.add(dataString[i]);
                }
            }
            
            root = getDeserializedTree(desData);
            
            return root;
        }
        
        
        private TreeNode getDeserializedTree(Queue<String> q)
        {
            String val = q.poll();
            if(val.equals("#"))
                return null;
            TreeNode root = new TreeNode(Integer.valueOf(val));
            root.left = getDeserializedTree(q);
            root.right = getDeserializedTree(q);
            
            return root;
        }
    }
    

Log in to reply
 

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