본문 바로가기
Programming/Algorithm

[leetcode] BinaryTreeLevelOrderTraversal

by 읽고 쓰는 개발자 2020. 11. 29.

https://leetcode.com/problems/binary-tree-level-order-traversal/

 

Binary Tree Level Order Traversal - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

import java.util.ArrayList;
import java.util.List;

public class BinaryTreeLevelOrderTraversal {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> answer = new ArrayList<>();
        if(root == null) return answer;

        ArrayList<Integer> list = new ArrayList<>();
        list.add(root.val);
        answer.add(list);

        levelOrder(root, 1, answer);
        return answer;
    }

    public void levelOrder(TreeNode root, int depth, List<List<Integer>> answer) {
        if(answer.size() < depth + 1) {
            ArrayList<Integer> list = new ArrayList<>();
            if(root.left != null) list.add(root.left.val);
            if(root.right != null) list.add(root.right.val);
            if(list.size() != 0 ) answer.add(list);
        }else {
            List<Integer> list = answer.get(depth + 1);
            if(root.left != null) list.add(root.left.val);
            if(root.right != null) list.add(root.right.val);
        }
        if(root.left != null) levelOrder(root.left, depth + 1, answer);
        if(root.right != null) levelOrder(root.right, depth + 1, answer);
    }
}

DFS로 해결한 이진트리 BinaryTreeLevelOrderTraversal

'Programming > Algorithm' 카테고리의 다른 글

[leetcode] MergeKLists  (0) 2020.11.29
[leetcode] MergeIntervals  (0) 2020.11.29
[leetcode] LRUCache  (0) 2020.11.29
[leetcode] IsValidSudoku  (0) 2020.11.29
[leetcode] intToRoman  (0) 2020.11.29