Collect elements matching a class name by walking a DOM subtree

Implement a function getElementsByClassName that mimics the behavior of the native DOM method document.getElementsByClassName. The function should search through a DOM tree starting from a specified root element and collect all elements that have the specified class name. For reference, see the native getElementsByClassName().
The function getElementsByClassName(className, root) takes two parameters: className, which is the name of the class to search for, and root, which is the root element of the DOM subtree in which to begin the search. If the root element is not provided, the search should not proceed.
The function should return an array of DOM elements that match the specified class name. If no elements are found, the function should return an empty array. The search should include the root element and should be performed depth-first, ensuring that all descendants of the root are considered.
Example:
// Assuming an HTML structure like:
// <div class="container">
// <div class="item active"></div>
// <div class="item"></div>
// <div class="list">
// <div class="item active"></div>
// </div>
// </div>
const rootElement = document.querySelector('.container');
const itemsWithActiveClass = getElementsByClassName('active', rootElement);
// itemsWithActiveClass should contain the two '.item.active' divs
This task requires traversing the DOM tree and applying conditional logic to select elements based on their class name, which is a common requirement in many frontend development tasks. Implementing this function will deepen your understanding of DOM manipulation and element selection.