Java Preorder DFS Solution, 15ms


  • 1
    J
    public class Codec {
    
        // Encodes a tree to a single string.
        // We use "," to seperate information and use "N" to denote null node.
        public String serialize(TreeNode root) {
            StringBuilder sb = new StringBuilder();
            serializeHelper(root, sb);
            return sb.toString();
        }
        
        private void serializeHelper(TreeNode root, StringBuilder sb) {
            // base case
            if (root == null) {
                sb.append("N").append(",");
                return;
            }
            // pre-order traversal.
            sb.append(root.val);
            sb.append(",");
            serializeHelper(root.left, sb);
            serializeHelper(root.right, sb);
        }
        
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            String[] splitInfo = data.split(",");
            int[] index = new int[]{0};
            return deserializeHelper(splitInfo, index);
        }
        
        private TreeNode deserializeHelper(String[] splitInfo, int[] index) {
            // base case
            if (index[0] == splitInfo.length) {
                return null;
            }
            String cur = splitInfo[index[0]];
            if (cur.equals("N")) {
                return null;
            } else {
                TreeNode curRoot = new TreeNode(Integer.valueOf(cur));
                index[0] ++;
                curRoot.left = deserializeHelper(splitInfo, index);
                index[0] ++;
                curRoot.right = deserializeHelper(splitInfo, index);
                return curRoot;
            }
        }
        
    }
    
    

  • 0
    J
    This post is deleted!

Log in to reply
 

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