simple recursive java solution


  • 0
    S
    public class Codec {
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            if(root==null) return "n";
            String result = String.valueOf(root.val);
            result = result + "(" + serialize(root.left) + ")(" + serialize(root.right) + ")";
            return result;
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            TreeNode node = null;
            if(data.charAt(0)!='n'){
                int index = 0;
                while(data.charAt(index)!='(') index++;
                String root = data.substring(0,index);
                int count = 1;
                index++;
                int start = index;
                while(count>0) {
                    if(data.charAt(index)=='(') count++;
                    if(data.charAt(index)==')') count--;
                    index++;
                }
                String left = data.substring(start,index-1);
                String right = data.substring(index+1,data.length()-1);
                node = new TreeNode(Integer.parseInt(root));
                node.left = deserialize(left);
                node.right = deserialize(right);
            }
            return node;
        }
    }
    

Log in to reply
 

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