Easy understand java solution, preorder+recursion


  • 0
    E
    public class Codec {
    
        private final String spliter = " ";
        private final String NN = "#";
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            StringBuffer sb = new StringBuffer();
            buildString(root, sb);
            return sb.toString();
        }
        
        private void buildString(TreeNode node, StringBuffer sb) {
            if(node==null){
                sb.append(NN).append(spliter);
            }else{
                sb.append(node.val).append(spliter);
                buildString(node.left, sb);
                buildString(node.right, sb);
            }
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if(data==null)
                return null;
            Queue<String> nodes = new LinkedList<String>();
            nodes.addAll(Arrays.asList(data.split(spliter)));
            String val = nodes.remove();
            if(val.equals(NN))
                return null;
            else
                return buildTree(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.valueOf(val), nodes);
        }
        
        private TreeNode buildTree(int min, int max, int val, Queue<String> nodes) {
            if(val>min && val<max){
                TreeNode node = new TreeNode(val);
                String s = nodes.remove();
                if(!s.equals(NN)){
                    node.left = buildTree(min, val, Integer.valueOf(s), nodes);
                }
                s = nodes.remove();
                if(!s.equals(NN)){
                    node.right = buildTree(val, max, Integer.valueOf(s), nodes);
                }
                return node;
            }
            return null;
        }
    }
    

Log in to reply
 

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