-
Notifications
You must be signed in to change notification settings - Fork 0
Balanced Binary Tree #95
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tom4649
wants to merge
2
commits into
main
Choose a base branch
from
110.Balanced-Binary-Tree
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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` のハッシュを固定の定数にする変更**が入った。 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| 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: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. -1 がマジックナンバーになってしまっているのが気になりました。 UNBALANCED 等定数に置いたほうが、理解しやすくなると思います。
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
最初に node を追加することで、子を調べたあとで戻ってきて調べることができるという点が、ややパズルに感じました。個人的には acceptable だと感じました。
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
再帰で書く方が自然だと思います。