Algorithms and Data Structures/Coding Practices

CCI 4.3 List of Depths

brightlightkim 2022. 6. 2. 15:31

Given a binary tree, design an algorithm that creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists).

 

void createLevelLinkedList(TreeNode root, ArrayList<LinkedList<TreeNode>> lists, int level){
    if (root == null) return; //base case

    LinkedList<TreeNode> list = null;
    if (lists.size() == level) {
        list = new LinkedList<TreeNode>();
        /**
         * Levels are always traversed in order. So, if this is the first time we've
         * visited level i, we must have seen levels 0 through i -1. We can
         * therefore safely add the level at the end.
         */
        lists.add(list);
    } else {
        list = lists.get(level);
    }
    list.add(root);
    createLevelLinkedList(root.left, lists, level + 1);
    createLevelLinkedList(root.right, lists, level + 1);
}

ArrayList<LinkedList<TreeNode>> createLevelLinkedList(TreeNode root) {
    ArrayList<LinkedList<TreeNode>> lists = new ArrayList<LinkedList<TreeNode>>();
    createLevelLinkedList(root, lists, 0);
    return lists;
}

'Algorithms and Data Structures > Coding Practices' 카테고리의 다른 글

LeetCode 374. Guess Number Higher or Lower  (0) 2022.06.04
LeetCode 704. Binary Search  (0) 2022.06.03
CCI 4.1 Route Between Nodes  (0) 2022.05.31
[Stacks and Queues] CCI 3.1  (0) 2022.05.22
[LinkedList] CCI 2.1  (0) 2022.05.20