Java AC Solution, beats 95% of all submissions


  • 0
    W

    The idea is to serialize in-order with 'x' representing a null node.

    public class Codec {
        int index = 0;
        
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            StringBuilder sb = new StringBuilder();
            
            if (root != null) {
                serialize(root, sb);
            }
            
            String s = sb.toString().trim();
            return s;
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if (data.length() == 0) return null;
    
            String[] split = data.split(" ");
            index = 0;
            TreeNode root = deserialize(split);
            return root;
        }
        
        private void serialize(TreeNode root, StringBuilder sb) {
            if (root == null) {sb.append("x "); return; }
            sb.append(root.val + " ");
            serialize(root.left, sb);
            serialize(root.right, sb);
        }
        
        private TreeNode deserialize(String[] data) {
            if (index >= data.length || data[index].equals("x")) {
                index++; 
                return null;
            }
            
            TreeNode root = new TreeNode(Integer.parseInt(data[index++]));
            root.left = deserialize(data);
            root.right = deserialize(data);
            return root;
        }
    }
    

Log in to reply
 

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