Java Stack based solution using JSON


  • 5
    Q
    public class Codec {
        public String serialize(TreeNode root) {
    		return root==null?"n":"[v:"+root.val+
    		    ",l:"+serialize(root.left)+",r:"+serialize(root.right)+"]";
        }
        public TreeNode deserialize(String data) {
        	Deque<String> stack = new LinkedList<String>();
        	Deque<TreeNode> nodeStack = new LinkedList<TreeNode>();
        	StringBuilder sb = new StringBuilder();
        	for (char c: data.toCharArray()){
        		if (c == '[' || c == ',' || c == ']'){
        			stack.push(sb.toString());
        			sb.setLength(0);
                    stack.push(String.valueOf(c));
                    if (c == ']'){
            			TreeNode t = new TreeNode(0);
            			String str = null;
            			while (!(str = stack.pop()).equals("["))
            				if (str.startsWith("v:"))
            					t.val = Integer.parseInt(str.substring(2));
            				else if (str.equals("l:"))
            					t.left = nodeStack.pop();
            				else if (str.equals("r:"))
            					t.right = nodeStack.pop();
            			nodeStack.push(t);
            		}
        		}
        		else
        			sb.append(c);
        	}
    		return nodeStack.isEmpty()?null:nodeStack.pop();
    	}
    }

Log in to reply
 

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