Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions 0110.Balanced-Binary-Tree/memo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# 110. Balanced Binary Tree

## step1

再帰でpost-orderのDFSを実装した。

## step2

### 他の人のコード
https://github.com/huyfififi/coding-challenges/pull/11/changes

> いや、私の良くするたとえ話としてね、木の全ノードに部下を立たせるんですよ。
> そうすると、nonlocal って、部下たちのいる部屋に共通の看板を立てておいて、全部下がその看板に書いたり消したりするんですよね。
> それだったら、部下同士のやり取り(関数呼び出し)の中で、自分より下の部分の `max_sum` の情報も報告するようにしたほうがスマートじゃないでしょうか、ということです。
> たとえば、こっちの方がスレッド増やしたくなったときに並列性が良さそうです。

nonlocal に頼らず「子から親へ情報を返す」ほうがスマート


https://github.com/ryosuketc/leetcode_grind75/pull/11/changes

https://github.com/Kitaken0107/GrindEasy/pull/16

この解法はO(n^2)となるが自分は逆にこれを思いつかなかった


ループに書き直すもの(辞書を使う)、ブール値を変えさず-1で処理するもの、望ましくない実装、を書いておく

書く中で None も dict のキーにできる -> **hashable** だと気づいた(これまで意識していなかった)。

昔のはなし
https://stackoverflow.com/questions/7681786/how-is-hashnone-calculated

- **昔の CPython(議論の中心だった頃)**: `hash(None)` は **`id(None)` を材料にした通常のオブジェクト用ハッシュ**(アドレスをビットいじりしたもの)になっていた、という説明が有力。**`None` は `_Py_NoneStruct` のように C 側で一個だけ用意されるシングルトン**なので、**同一ビルド・同一環境ではインタプリタを再起動してもメモリ上の位置が(かなりの確率で)変わらず、`hash(None)` も同じ値に見える**、というのが受け付け回答の趣旨。**別ビルド・別マシンでは値が変わりうる**点もセット。
- **実装の話と言語モデル**: **キーに必要なのは hashable(不変な同一性・ハッシュの安定)などの条件で、`None` はシングルトンとしてそれを満たす**。
- **Python 3.12 以降**: [CPython PR #99541](https://github.com/python/cpython/pull/99541) で、**再現性の支援のため `None` のハッシュを固定の定数にする変更**が入った。
22 changes: 22 additions & 0 deletions 0110.Balanced-Binary-Tree/step1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def is_balanced_helper(node):
if node is None:
return True, 0

is_balanced_left, height_left = is_balanced_helper(node.left)
is_balanced_right, height_right = is_balanced_helper(node.right)
is_balanced = (
is_balanced_left
and is_balanced_right
and abs(height_left - height_right) <= 1
)
return is_balanced, max(height_left, height_right) + 1

return is_balanced_helper(root)[0]
65 changes: 65 additions & 0 deletions 0110.Balanced-Binary-Tree/step2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
node_to_height = {None: 0}
stack = [root]

while stack:
node = stack.pop()
if node is None:
continue

height_left = node_to_height.get(node.left)
height_right = node_to_height.get(node.right)

if height_left is None or height_right is None:
stack.append(node)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

最初に node を追加することで、子を調べたあとで戻ってきて調べることができるという点が、ややパズルに感じました。個人的には acceptable だと感じました。

Copy link
Copy Markdown
Owner Author

@tom4649 tom4649 May 19, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

再帰で書く方が自然だと思います。

stack.append(node.right)
stack.append(node.left)
continue

if abs(height_left - height_right) > 1:
return False

node_to_height[node] = max(height_left, height_right) + 1

return True


class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def height_or_unbalanced(node: Optional[TreeNode]) -> int:
if node is None:
return 0
left_h = height_or_unbalanced(node.left)
if left_h == -1:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

-1 がマジックナンバーになってしまっているのが気になりました。 UNBALANCED 等定数に置いたほうが、理解しやすくなると思います。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ご指摘の通りだと思います。修正しました。

return -1
right_h = height_or_unbalanced(node.right)
if right_h == -1:
return -1
if abs(left_h - right_h) > 1:
return -1
return max(left_h, right_h) + 1

return height_or_unbalanced(root) != -1


# 望ましくない実装。時間計算量が最悪でO(n^2)
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if root is None:
return True

def depth(node: Optional[TreeNode]) -> int:
if node is None:
return 0
return 1 + max(depth(node.left), depth(node.right))

if abs(depth(root.left) - depth(root.right)) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
67 changes: 67 additions & 0 deletions 0110.Balanced-Binary-Tree/step2_retry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
node_to_height = {None: 0}
stack = [root]

while stack:
node = stack.pop()
if node is None:
continue

height_left = node_to_height.get(node.left)
height_right = node_to_height.get(node.right)

if height_left is None or height_right is None:
stack.append(node)
stack.append(node.right)
stack.append(node.left)
continue

if abs(height_left - height_right) > 1:
return False

node_to_height[node] = max(height_left, height_right) + 1

return True


class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
UNBALANCED = -1

def height_or_unbalanced(node: Optional[TreeNode]) -> int:
if node is None:
return 0
left_h = height_or_unbalanced(node.left)
if left_h == UNBALANCED:
return UNBALANCED
right_h = height_or_unbalanced(node.right)
if right_h == UNBALANCED:
return UNBALANCED
if abs(left_h - right_h) > 1:
return UNBALANCED
return max(left_h, right_h) + 1

return height_or_unbalanced(root) != UNBALANCED


# 望ましくない実装。時間計算量が最悪でO(n^2)
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if root is None:
return True

def depth(node: Optional[TreeNode]) -> int:
if node is None:
return 0
return 1 + max(depth(node.left), depth(node.right))

if abs(depth(root.left) - depth(root.right)) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)