Open In App

How to set the order in subnodes of a tree structure?

Improve
Improve
Like Article
Like
Save
Share
Report

What is the order of a tree?

The arrangement or positioning of a tree structure’s nodes and subnodes in relation to one another is referred to as the tree structure’s “order.” The preferred order of each node’s subnodes can be determined by a specific feature or characteristic of each node, such as a number or text.

We can sort a tree structure’s nodes and subnodes depending on this property and present them in a meaningful fashion that highlights the connections between nodes by adjusting the tree structure’s order. This makes it simpler to see the connections between the tree’s nodes and spot any patterns or hierarchies in the data.

How to set the order in a tree?

Subnodes in a tree structure can be arranged in any order by specifying an attribute in each node that corresponds to the preferred arrangement of its subnodes. This characteristic, which is used for comparison, could be either a string or a numerical value. Once the order attribute is specified, a sorting algorithm may be used to sort the subnodes depending on their order attribute. Integrated sorting functions or custom sorting functions that compare the subnodes’ order attributes can be used to accomplish the algorithm. The tree structure can be arranged and displayed in a meaningful fashion that shows the links between nodes by defining the order of the subnodes.

Example: To set the order of subnodes in a tree structure, we need to define an attribute in the node object that represents the order of the subnodes. Then, you can use a sorting algorithm to sort the subnodes based on the order attribute.

Approach: Follow the below steps to set the order in a tree:

  • Define a node object with a subnode property that contains an array of subnodes. Each subnode object contains a name property and an order property that represents the desired order of the subnode within the parent node.
  • To sort the subnodes based on the order property, we use the sort() method of the array object, passing in a comparison function that compares the order property of each subnode. This sorts the subnodes in ascending order of the order property.
  • Print the sorted subnodes by iterating over the subnode array and accessing the name property of each subnode.

Here is an example implementation in JavaScript:

C++




#include <iostream>
#include <vector>
#include <algorithm>
 
struct Node {
    std::string name;
    std::vector<Node> subnodes;
};
 
int main() {
    Node node = {
        "Node A",
        {
            { "Node A.2", {} },
            { "Node A.3", {} },
            { "Node A.1", {} }
        }
    };
 
    // Sort the subnodes based on the name
    std::sort(node.subnodes.begin(), node.subnodes.end(),
              [](const Node& a, const Node& b) { return a.name < b.name; });
 
    // Print the sorted subnodes
    for (const auto& subnode : node.subnodes) {
        std::cout << subnode.name << std::endl;
    }
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
class Node {
    String name;
    List<Node> subnodes;
 
    Node(String name, List<Node> subnodes) {
        this.name = name;
        this.subnodes = subnodes;
    }
}
 
public class Main {
    public static void main(String[] args) {
        Node node = new Node("Node A", new ArrayList<>() {{
            add(new Node("Node A.2", new ArrayList<>()));
            add(new Node("Node A.3", new ArrayList<>()));
            add(new Node("Node A.1", new ArrayList<>()));
        }});
 
        // Sort the subnodes based on the name
        Collections.sort(node.subnodes, Comparator.comparing((Node n) -> n.name));
 
        // Print the sorted subnodes
        for (Node subnode : node.subnodes) {
            System.out.println(subnode.name);
        }
    }
}
// This code was contributed by codearcade


Python3




class Node:
    def __init__(self, name, subnodes):
        self.name = name
        self.subnodes = subnodes
 
if __name__ == "__main__":
    node = Node("Node A", [
        Node("Node A.2", []),
        Node("Node A.3", []),
        Node("Node A.1", [])
    ])
 
    # Sort the subnodes based on the name
    node.subnodes.sort(key=lambda x: x.name)
 
    # Print the sorted subnodes
    for subnode in node.subnodes:
        print(subnode.name)
# This code is contributed by Dwaipayan Bandyopadhyay


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Node
{
    public string Name { get; set; }
    public List<Node> Subnodes { get; set; } = new List<Node>();
}
 
class Program
{
    static void Main()
    {
        Node node = new Node
        {
            Name = "Node A",
            Subnodes = new List<Node>
            {
                new Node { Name = "Node A.2" },
                new Node { Name = "Node A.3" },
                new Node { Name = "Node A.1" }
            }
        };
 
        // Sort the subnodes based on the name
        node.Subnodes = node.Subnodes.OrderBy(subnode => subnode.Name).ToList();
 
        // Print the sorted subnodes
        foreach (var subnode in node.Subnodes)
        {
            Console.WriteLine(subnode.Name);
        }
    }
}


Javascript




var node = {
  name: "Node A",
  subnodes: [
    { name: "Node A.2", order: 2 },
    { name: "Node A.3", order: 3 },
    { name: "Node A.1", order: 1 }
  ]
};
 
// Sort the subnodes based on the order attribute
node.subnodes.sort(function(a, b) {
  return a.order - b.order;
});
 
// Print the sorted subnodes
for (var i = 0; i < node.subnodes.length; i++) {
  console.log(node.subnodes[i].name);
}


Output

Node A.1
Node A.2
Node A.3





Time Complexity: O(n*logn)
Auxiliary Space: O(1)



Last Updated : 17 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads