Skip to content

Create 11.Balanced Binary Tree.md#16

Open
Kitaken0107 wants to merge 1 commit intomainfrom
Kitaken0107-patch-18
Open

Create 11.Balanced Binary Tree.md#16
Kitaken0107 wants to merge 1 commit intomainfrom
Kitaken0107-patch-18

Conversation

@Kitaken0107
Copy link
Owner

# self.left = left
# self.right = right
class Solution:
def height(self,root:TreeNode) -> bool:
Copy link

Choose a reason for hiding this comment

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

同じノードに対し、同じ処理を複数回行っており、コンピューターリソースがもったいないように思います。キャッシュを撮ってはいかがでしょうか?

Copy link
Owner Author

Choose a reason for hiding this comment

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

コメントありがとうございます
キャッシュ書いてみたことないのですが、トライしてみます!

Copy link

@hayashi-ay hayashi-ay left a comment

Choose a reason for hiding this comment

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

再帰の処理をよくよく追っていくとheightとisBalancedでノードを同じように辿っているので一緒にしてしまうという選択肢もあると思います。

def isBalanced(self,root:TreeNode) -> bool:
if not root:
return True
return abs(self.height(root.left)-self.height(root.right)) < 2 and self.isBalanced(root.left) and self.isBalanced(root.right)

Choose a reason for hiding this comment

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

チェックする順番的に以下の方が自然かなという気がしました。

  • 左右の子ノードについてバランスしているか
  • 自信のノードについてバランスしているか

Choose a reason for hiding this comment

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

好みのかもしれないですが。

if not self.isBalanced(root.left):
   return False
if not self.isBalanced(root.right):
  return False
return 自分自信のノードがバランスしているか

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます
・再起をひとまとめにする
・バランスしているかの確認の順番、左右を先にしたほうがよさそうですね
(特に再起をひとまとめにすると、そうしたほうが自然)
・一つのreturn文にまとめすぎると読むの大変(構造見えるようにしたほうが読みやすい)のは、たしかにそうですね
直してみます!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants