请构建一个接受边数组的函数,构造整棵树并返回根节点 1

问题描述 投票:0回答:0

一些重要的注意事项: • 1 是根节点 • 没有重复的边缘 • 没有孤立的节点 • 因此 N 个节点,n-1 条边 • 元组中的位置不指示方向 示例树节点类: 节点{

整数值; 列出孩子;

}

这是我到目前为止所拥有的,我只得到输出而不是整棵树: 1个 5个 3

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class App {
    public static void main(String[] args) throws Exception {
        int[][] biArray = {
            {4, 5},
            {5, 3},
            {1, 5},
            {2, 1}
        };
        App app = new App();
        Node root = app.constructTree(biArray);
        displayTree(root);

    }


    public static class Node {
        int data;
        List<Node> children;
        public Node(int data){
            this.data = data;
            this.children = new ArrayList<>();
        }
    
        public void addChild(Node node){
            children.add(node);
        }
    
        public List<Node> getChildren(){
            return children;
        }
    
        public int getData(){
            return data;
        }
    }

    public Node constructTree(int[][] edges) {
        Map<Integer, Node> nodeMap = new HashMap<>();
        for (int[] edge : edges) {
            int parentValue = edge[0];
            int childValue = edge[1];
            Node parentNode = nodeMap.getOrDefault(parentValue, new Node(parentValue));
            Node childNode = nodeMap.getOrDefault(childValue, new Node(childValue));
            parentNode.children.add(childNode);
            nodeMap.put(parentValue, parentNode);
            nodeMap.put(childValue, childNode);
        }
        return nodeMap.get(1);
    }
    
    public static void displayTree(Node root) {
        System.out.println(root.getData());
        for (Node child : root.getChildren()) {
            displayTree(child);
        }
    }

}



java algorithm tree tuples nodes
© www.soinside.com 2019 - 2024. All rights reserved.