SMALL

Given the root of a binary tree, return the leftmost value in the last row of the tree.

 

이진트리의 루트가 주어지고, 트리의 가장 밑에 왼쪽 값을 리턴해라.


이 문제에서는 특정한 레벨의 값을 찾는 문제이므로, 레벨별로 트리를 탐색하는 bfs 알고리즘을 사용하는 것이 좋을 것이다. 또한 가장 왼쪽의 값이라면, bfs에서 트리를 탐색할 때 방문한 노드의 왼쪽 값부터 queue에 넣는다면 방문한 레벨의 첫 번째 값이 가장 왼쪽에 존재하는 값이 될 것이다.

 

    public int findBottomLeftValue(TreeNode root) {

        Queue<TreeNode> queue = new LinkedList<>();

        if (root == null) {
            return 0;
        }
        queue.add(root);

        int rst = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (i == 0) {
                    rst = node.val;
                }

                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        return rst;
    }

 

문제 출처 : 

leetcode.com/problems/find-bottom-left-tree-value/

 

Find Bottom Left Tree Value - 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

 

LIST

+ Recent posts