[编程题]Department list to tree(Convert the department list to preorder traversal of the name of depar)

Convert the department list to preorder traversal of the name of department tree

示例1
输入
[[“d1”, “d0”, “IT”], [“d2”, “d0”, “RD”], [“d0”, “”, “The Company”], [“d3”, “d0”, “HR”]]

输出
[“The Company”,“HR”,“IT”,“RD”]

说明
On each level of the department tree, departments are listed in alphabetical order of the name

import java.util.*;

/**
 * 规律:先序遍历 但是每一层要按照字典序进行
 */
public class Solution {
    /**
     * Convert the department list to preorder traversal of the department tree
     * @param departments string字符串二维数组 [["id1", "parentId", "name"]...], there's only one root department with empty parent id.
     * @return string字符串一维数组
     */
     /**
     * 节点结构
     */
    class Node {
        String id;
        List<Node> sons;
        String name;

        Node(String id, String name) {
            this.id = id;
            this.sons = new ArrayList<>();
            this.name = name;
        }
    }

    List<String> res = new ArrayList<>();

    public String[] listToTree(String[][] departments) {
        System.out.println("z".compareTo("def"));
        //排序 每一层按照字典序进行
        for (int i = 0; i < departments.length; i++) {
            for (int j = i + 1; j < departments.length; j++) {
                if (departments[i][2].compareTo(departments[j][2]) > 0) {
                    String[] temp = departments[i];
                    departments[i] = departments[j];
                    departments[j] = temp;
                }
            }
        }
        //记录父节点
        Deque<String> parents = new ArrayDeque<>();
        //hashMap id Node
        HashMap<String, Node> hashMap = new HashMap<>();
        //超级节点
        hashMap.put("", new Node("", ""));
        //添加节点
        for (int i = 0; i < departments.length; i++) {
            //添加一个节点
            Node n = new Node(departments[i][0], departments[i][2]);
            hashMap.put(departments[i][0], n);
        }
        //添加儿子节点
        for (int i = 0; i < departments.length; i++) {
            //添加一个节点
            hashMap.get(departments[i][1]).sons.add(hashMap.get(departments[i][0]));
        }
        //先序
        preOrder(hashMap, hashMap.get("").sons.get(0).id);
        String[] result = new String[departments.length];
        for (int i = 0; i < res.size(); i++) {
            result[i] = res.get(i);
        }
        return result;
    }

    /**
     * 先序遍历
     *
     * @param hashMap
     * @param curNodeId
     */
    public void preOrder(HashMap<String, Node> hashMap, String curNodeId) {

        res.add(hashMap.get(curNodeId).name);
        if (hashMap.get(curNodeId).sons.size() == 0) {
            return;
        }
        for (Node n : hashMap.get(curNodeId).sons) {
            preOrder(hashMap, n.id);
        }
    }
}

你可能感兴趣的:(笔试题,java,数据结构)