recursive java solution


  • 0
    F
    public class Codec {
        public String serialize(TreeNode root) {
            return serialize(root, new StringBuilder()).toString();
        }
    
        private StringBuilder serialize(TreeNode root, StringBuilder stringBuilder) {
            if (root == null) {
                return stringBuilder.append("null").append("#");
            }
            stringBuilder.append(root.val).append("#");
            serialize(root.left, stringBuilder);
            serialize(root.right, stringBuilder);
            return stringBuilder;
        }
    
        public TreeNode deserialize(String data) {
            LinkedList<String> stack = new LinkedList<>(Arrays.asList(data.split("#")));
            return deserialize(stack);
        }
    
        private TreeNode deserialize(LinkedList<String> stack) {
            String cur = stack.pop();
            if (cur.equals("null")) {
                return null;
            }
            TreeNode treeNode = new TreeNode(Integer.valueOf(cur));
            treeNode.left = deserialize(stack);
            treeNode.right = deserialize(stack);
            return treeNode;
        }
    }

Log in to reply
 

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