Java Easy to Understand o(N²) Recursive Solution


  • 1
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        StringBuilder sb = new StringBuilder();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                sb.append(root.val);
                sb.append(" ");
                root = root.left;
            }
            root = stack.pop();
            root = root.right;
        }
        return sb.toString();
    }
    
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data.equals("")) return null;
        String[] nums = data.split(" ");
        return buildTree(nums);
    }
    
    private TreeNode buildTree(String[] nums) {
        if (nums.length == 0) return null;
        TreeNode root = new TreeNode(Integer.valueOf(nums[0]));
        if (nums.length == 1) return root;
        int i = indexOfNextBiggerNumber(nums, root.val);
        String[] arrL = Arrays.copyOfRange(nums, 1, i);
        String[] arrR = Arrays.copyOfRange(nums, i, nums.length);
        root.left  = buildTree(arrL);
        root.right = buildTree(arrR);
        return root;
    }
    
    private int indexOfNextBiggerNumber(String[] s, int x) {
        for (int i = 0; i < s.length; i++)
            if (Integer.valueOf(s[i]) > x)
                return i;
        return s.length;
    }
    

Log in to reply
 

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