본문 바로가기
LeetCode/Top Interview Q. - Easy

LeetCode. Binary Tree Level Order Traversal [Trees]

by 벤진[Benzene] 2020. 6. 7.

Problem:

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

-Summary-

Solve by BFS (Breadth-First Search) Algorithm using queue

1. Create a queue and keep adding the value if left or right subtree exists

2. While adding the value to the queue, we pop and add the value to the 'res' list.

3. Once all nodes visited by each level, it will return the correct answer. 

 

BFS 가 아닌 DFS로도 풀수있는 방법이 discussion에 있었다.

leetcode.com/problems/binary-tree-level-order-traversal/discuss/33731/Python-short-dfs-solution

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

댓글