如何根据给定的节点号随机生成二叉树?

时间:2019-07-03 15:43:26

标签: java algorithm binary-tree

//Definition for a binary tree node.

public class TreeNode {
    int key;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { key = x; }
} 

给出TreeNode int n的总数,如何生成随机分布的二叉树(我的意思是二叉树的 random 形状,不是< / strong>随机键值。您可以将TreeNode的所有键值设置为1)并返回TreeNode root

这是实现以下API的方法:

public class RandomBinaryTree{
    public TreeNode binaryTreeGenerator(int n){

    }
}

PS:例如n = 3,我希望算法可以每次随机生成以下5个二进制树之一

     1      1        1           1          1
    /      /        / \           \          \
   1      1        1   1           1          1
  /        \                      /            \
 1          1                    1              1

是否有任何算法可生成具有固定数量的节点n的二叉树?

1 个答案:

答案 0 :(得分:5)

有偏分布,简单算法

从根开始,随机选择每个子树中的节点数,然后递归:

public class RandomBinaryTree {
    private Random random = new Random();

    public TreeNode binaryTreeGenerator(int n, int key){
        if (n == 0)
            return null;

        TreeNode root = new TreeNode(key);

        // Number of nodes in the left subtree (in [0, n-1])
        int leftN = random.nextInt(n);

        // Recursively build each subtree
        root.setLeft(binaryTreeGenerator(leftN, key));
        root.setRight(binaryTreeGenerator(n - leftN - 1, key));

        return root;
    }
}

此算法不强制执行结果的均匀分布,并且将非常倾向于平衡树。为简单起见,请考虑情况n = 3并计算5种可能的二叉树中每一个的出现概率(有关组合的信息,请参见Catalan numbers)。

分布均匀,更具挑战性

对此主题已有一些研究,this可能是最简单,最快的方法之一(在 O(n)中)。想法是生成一个随机单词,该单词包含相等数目的左右括号,然后使用保留统一分布的变换将其映射到二叉树。

第1步::生成随机的平衡词

private static Random random = new Random();

// true means '(', false means ')'
private static boolean[] buildRandomBalancedWord(int n) {
    boolean[] word = new boolean[n * 2];
    List<Integer> positions = IntStream.range(0, 2 * n).boxed()
        .collect(Collectors.toList());
    for (int i = n; i > 0; i--) {
        int index = random.nextInt(n + i);
        word[positions.remove(index)] = true;
    }
    return word;
}

第2步::生成的单词可能包含k个“缺陷”,基本上是不匹配的右括号。该论文表明,有一种方法可以重新排列生成的单词,从而使生成的映射是从具有k缺陷的单词集到具有0缺陷的单词集的双射(形式的单词)。步骤如下:

private static void rearrange(boolean[] word, int start, int end) {
    int sum = 0;
    int defectIndex = -1;
    for (int i = start; i < end; i++) {
        sum = sum + (word[i] ? 1 : -1);
        if (defectIndex < 0 && sum < 0) {
            defectIndex = i;
        } else if (defectIndex >= 0 && sum == 0) {
            // We now have irreducible u = rtl spanning [defectIndex, i]
            int uLength = i - defectIndex + 1;
            boolean[] flipped = new boolean[uLength - 2];
            for (int j = 0; j < flipped.length; j++)
                flipped[j] = !word[defectIndex + j + 1];

            // Shift the remaining word
            if (i + 1 < end)
                System.arraycopy(word, i + 1, word, defectIndex + 1, end - (i + 1));

            // Rewrite uw as lwrt*, t* being the flipped array
            word[defectIndex] = true;
            System.arraycopy(flipped, 0, word, end - flipped.length, flipped.length);
            word[end - uLength + 1] = false;

            // Now recurse on w, worst case we go (word.length/2)-deep
            rearrange(word, defectIndex + 1, end - uLength + 1);
            break;
        }
    }
}

第3步::从格式正确的括号词到二叉树有一对一的映射:每对匹配的括号都是一个节点,里面的所有内容都是左子树,所有内容之后是正确的子树:

// There is probably a smarter way to do this
public static TreeNode buildTree(boolean[] word, int key) {
    Deque<TreeNode> stack = new ArrayDeque<>();
    boolean insertRight = false;
    TreeNode root = null;
    TreeNode currentNode = null;
    for (int i = 0; i < word.length; i++) {
        if (word[i]) {
            TreeNode previousNode = currentNode;
            currentNode = new TreeNode(key);

            if (root == null) {
                root = currentNode;
            } else if (insertRight) {
                previousNode.setRight(currentNode);
                insertRight = false;
            } else {
                previousNode.setLeft(currentNode);
            }

            stack.push(currentNode);
        } else {
            currentNode = stack.pop();
            insertRight = true;
        }
    }
    return root;
}

某些实用程序功能

public static boolean[] buildRandomWellFormedWord(int n) {
    boolean[] word = buildRandomBalancedWord(n);
    rearrange(word, 0, word.length);
    return word;
}

public static String toString(boolean[] word) {
    StringBuilder str = new StringBuilder();
    for (boolean b : word)
        str.append(b ? "(" : ")");
    return str.toString();
}

测试:让我们在大小为3的一千万次运行中打印实际分布:

public static void main(String[] args) throws Exception {
    Map<String, Integer> counts = new HashMap<String, Integer>();
    int N = 10000000, n = 3;
    for (int i = 0; i < N; i++) {
        boolean[] word = buildRandomWellFormedWord(n);
        String str = toString(word);
        Integer count = counts.get(str);
        if (count == null)
            count = 0;
        counts.put(str, count + 1);
    }

    counts.entrySet().stream().forEach(e -> 
        System.out.println("P[" + e.getKey() + "] = " + e.getValue().doubleValue() / N));
}

输出应类似于:

P[()()()] = 0.200166
P[(()())] = 0.200451
P[()(())] = 0.199894
P[((()))] = 0.199006
P[(())()] = 0.200483

因此buildTree(buildRandomWellFormedWord(n), key)将在所有可能的树上均匀分布之后,生成大小为n的二叉树。