easy to understand java solution


  • 0
    F

    construct binary tree from preorder and inorder traversal:

        public String serialize(TreeNode root) {
            StringBuilder stringBuilder = new StringBuilder();
            preOrder(root, stringBuilder);
            return stringBuilder.toString().trim();
        }
    
        public TreeNode deserialize(String data) {
            if (data == null || data.isEmpty()) {
                return null;
            }
            String[] nums = data.split(" ");
            int n = nums.length;
            int[] preorder = new int[n];
            for (int i = 0; i < n; i++) {
                preorder[i] = Integer.parseInt(nums[i]);
            }
            int[] inorder = preorder.clone();
            Arrays.sort(inorder);
            return buildTree(preorder, 0, n, inorder, 0, n);
        }
    
        private void preOrder(TreeNode root, StringBuilder stringBuilder) {
            if (root != null) {
                stringBuilder.append(root.val).append(" ");
                preOrder(root.left, stringBuilder);
                preOrder(root.right, stringBuilder);
            }
        }
    
        private TreeNode buildTree(int[] preorder, int from1, int to1, int[] inorder, int from2, int to2) {
            if (from1 == to1) {
                return null;
            }
            int val = preorder[from1];
            TreeNode root = new TreeNode(val);
            int leftSize = 0;
            for (int i = from2; i < to2; i++) {
                if (inorder[i] == val) {
                    break;
                }
                leftSize++;
            }
            root.left = buildTree(preorder, from1 + 1, from1 + 1 + leftSize, inorder, from2, from2 + leftSize);
            root.right = buildTree(preorder, from1 + 1 + leftSize, to1, inorder, from2 + 1 + leftSize, to2);
            return root;
        }
    

Log in to reply
 

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