سؤال

I need to write a function that finds a node with the most children and return the number of children. The function should have a pointer to the root of a tree as input. Can someone provide a possible pseudocode for this function? I'm getting confused about the concept of first child and sibling pointers.

Thank you!

هل كانت مفيدة؟

المحلول

Recursive pseudocode with firstChild and nextSibling:

int maxChildren = findMaxChildren(root, 0);

int findMaxChildren(TreeNode root, int max) {
    if (root.getChildren().length > max) max = root.getChildren().length;
    TreeNode e = root.firstChild();
    while (e != null) {
        int tmp = findMaxChildren(e, max);
        if (tmp > max) max = tmp;
        e = e.nextSibling();        
    }
    return max;
}

نصائح أخرى

Recursively.

int maxChildren = findMaxChildren(root, 0);

int findMaxChildren(TreeNode root, int max) {
    if (root.getChildren().length > max) max = root.getChildren().length;
    for (TreeNode e : root.getChildren()) {
        int tmp = findMaxChildren(e, max);
        if (tmp > max) max = tmp;
    }
    return max;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top