如何将已排序的数组转换为BST?

时间:2015-04-05 23:31:14

标签: java arrays binary-search-tree

我努力在下面获得我想要的输出。这就是我到目前为止所做的,我认为我已接近完成。

import java.util.Scanner;

public class sortedArrayBST {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        try {

            if (n <= 0) {
                input.close();
            }

            int m = input.nextInt();
            if (m <= 0) {
                input.close();
            }

            int[] s = new int[n];
            int[] w = new int[m];

            for (int i = 0; i < n; i++) {
                s[i] = input.nextInt();
            }
            for (int i = 0; i < m; i++) {
                w[i] = input.nextInt();
            }

        } catch (IllegalStateException e) {

        }
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode parent;

        TreeNode(int x) {
            val = x;
        }
    }

    public static TreeNode sortedArrayToBST(int[] num) {
        if (num == null || num.length == 0)
            return null;

        int start = 0, end = num.length - 1;

        TreeNode root = buildTree(num, start, end);

        return root;
    }

    public static TreeNode buildTree(int[] num, int start, int end) {

        if (start > end) {
            return null;
        }

        int mid = start + (end - start) / 2;
        TreeNode node = new TreeNode(num[mid]);

        node.left = buildTree(num, start, mid - 1);
        node.right = buildTree(num, mid + 1, end);

        return node;
    }
}

我必须接受用户输入,例如:

4 // denotes number of elements in array S, variable n.
2 // number of elements in array W, variable m.
0  // 0, 25, 33, 77 are in S.
25
33
77
19 // 19 and 40 are in W. 
40

这些数字代表句子的位置,所以每个句子的结尾。 输出是

2 // 2 words of interest found, this value is always the same as W above
1 25 // start of the sentence with 1st occurrence of word of interest (end      of previous sentence + 1) and end of the sentence (aka ".")
34 77 // so the previous sentence before this ended at position 33, so the next sentence started at 34, and it ends at 77.

IDK如何使用排序数组将其传送到BST。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,我认为你正在寻找的是一种遍历你构造的bst来以给定格式打印输出的方法。

如果是这种情况,你可以做一个inorder traversal的树来实现它。(虽然,有一个排序的数组,从中构造一个bst然后按排序的顺序打印bst是善良的一个矫枉过正的你不觉得吗?)

static boolean flag = false;
public static void inorderTraverse(TreeNode root){
    if(root == null) return;
    inorderTraverse(root.left);
    if(flag){
        System.out.print(root.val);
        System.out.print("\n");
        flag = false;
    }
    else{ 
        flag = true;
        System.out.print(root.val + 1 + " ");
    }
    inorderTraverse(root.right);
}