技術共有

Java ツリー構造リストのレベルを決定する方法

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

解決
アルゴリズムのアイデア
ツリー構造内のリストがどのレベルにあるかを判断するには、各ノードを再帰的に走査し、その深さを計算します。具体的には、各ノードについて、深さの値を累積しながら、その親ノードをルート ノードまで上にたどることができます。最終的な深さの値は、ノードが配置されているレベルです。

コード例
以下は、ツリー構造内のノードのレベルを決定するために使用される簡単な Java コードの例です。

public class TreeNode {
    private int id;
    private int parentId;

    public TreeNode(int id, int parentId) {
        this.id = id;
        this.parentId = parentId;
    }

    public int getId() {
        return id;
    }

    public int getParentId() {
        return parentId;
    }
}

public class TreeUtils {
    public static int getLevel(TreeNode node, List<TreeNode> nodeList) {
        int level = 1;
        int parentId = node.getParentId();
        
        while (parentId != 0) {
            for (TreeNode n : nodeList) {
                if (n.getId() == parentId) {
                    parentId = n.getParentId();
                    level++;
                    break;
                }
            }
        }
        
        return level;
    }
}

public class Main {
    public static void main(String[] args) {
        List<TreeNode> nodeList = new ArrayList<>();
        nodeList.add(new TreeNode(1, 0));
        nodeList.add(new TreeNode(2, 1));
        nodeList.add(new TreeNode(3, 1));
        nodeList.add(new TreeNode(4, 2));

        TreeNode node = nodeList.get(3);
        int level = TreeUtils.getLevel(node, nodeList);
        System.out.println("Node " + node.getId() + " is at level " + level);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50