スポンサーリンク

【LeetCode】637. Average of Levels in Binary Tree 解答・解説【Python】

スポンサーリンク
スポンサーリンク
この記事は約2分で読めます。

 

問題

原文

Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.

 

Example 1:

Example 2:

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -231 <= Node.val <= 231 - 1

 

内容

二分木rootが与えられるので、各階層の値の平均値を配列で返してください。

誤差は10^(-5)以内としてください。

 

 

※正しくない可能性があります。

 

解答

解答1:Python, BFS(幅優先探索)

 

 

幅優先探索

各階層の探索を行う際、valの合計値をsum_of_valueに、各階層のノードの数をlength_of_qにそれぞれ保存しておき、各階層の探索終了時に平均値を求めてanswerに追加する。

 

 

解答2:

 

 

 

メモ・参考・感想

 

 

 

前:107. Binary Tree Level Order Traversal II

次:202. Happy Number

LeetCode 解答・解説記事一覧

コメント