Java preorder solution


  • 0
    D
    public class Codec {
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            if (root == null) {
                return "#";
            }
            StringBuffer sb = new StringBuffer();
            sb.append(Integer.toString(root.val) + "#");
            sb.append(serialize(root.left));
            sb.append(serialize(root.right));
            return sb.toString();
        }
    
        private int cursor = 0;
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            cursor = 0;
            return _deserialize(data);
        }
    
        private TreeNode _deserialize(String data) {
            assert cursor < data.length();
            int pindex = data.indexOf('#', cursor);
            assert pindex < data.length();
            TreeNode root = null;
            if (pindex > cursor) {
                int val = Integer.parseInt(data.substring(cursor, pindex));
                cursor = pindex + 1;
                root = new TreeNode(val);
                root.left = _deserialize(data);
                root.right = _deserialize(data);
            } else {
                cursor++;
            }
            return root;
        }
    }
    

Log in to reply
 

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