Search code snippets, questions, articles...

Sort Tree - Bloomberg - Port Interactive Analytics - Front End - 12/6/21

// Let's assume you are given the world tree, wherein the first level represents continents, the second level represents countries, the third level represents states/provinces and so on. Write a method to re-arrange this tree in such a way that all children of every node are sorted in alphabetical order.
     World
    / 
  North America
    /                        \
    US                       Canada
    /     \       \ 
California  NYC  Alabama

Node {
    value
    children: Node[]
}

Tree {
 topNode: Node
}

function sortChildren(tree) {


    // Continents 
    tree.topNode.children.sort((childNode1, childNode2) => {
        if (childNode1.value < childNode2.value) {
            return -1;
        } else (childNode1.value > childNode2.value) {
            return 1; 
        }
        return 0;
    })
    
    tree.topNode.children.foreach((continent) => {
        continent.children.foreach((country) => {
            country.children.foreach((state) => {
                
            })
        })
    });
}

function sort(node) {
    if (node.children) {
        node.children.foreach(() => { sort(node)}))
    } else {
        // reached the end 
    }
}
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.
Was this helpful?
0 Comments