Skip to content

Conversation

@SuperHotDogCat
Copy link
Owner

if len(nums) == 1:
return TreeNode(nums[0])

add_node = TreeNode(val=nums[len(nums)//2])
Copy link

Choose a reason for hiding this comment

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

第 1 引数のため、 val= は無くても良いと思います。

return TreeNode(nums[0])

add_node = TreeNode(val=nums[len(nums)//2])
add_node.left = self.sortedArrayToBST(nums[:len(nums)//2])
Copy link

Choose a reason for hiding this comment

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

スライスを作るとコピーが発生し、処理が重くなるため、 phase2 のようにインデックスで処理したほうがよいと思います。

mid = (right + left) // 2
node = TreeNode(nums[mid])
node.left = build_bst(left, mid)
node.right = build_bst(mid+1, right)
Copy link

Choose a reason for hiding this comment

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

Surround binary operators with a single space on either side for assignment (=), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), and Booleans (and, or, not). Use your better judgment for the insertion of spaces around arithmetic operators (+, -, *, /, //, %, **, @).

Comment on lines +20 to +21
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def build_bst(left, right):

Choose a reason for hiding this comment

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

関数名が snake case だったり camel case だったりと統一されていないのが気になりました。
PEP 8 見る限りだと snake case が奨励されるみたいですね: https://peps.python.org/pep-0008/#function-and-variable-names

Choose a reason for hiding this comment

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

ああ、 Leetcode が指定する関数だから変えられないんですね。これは悩ましい...

Copy link
Owner Author

Choose a reason for hiding this comment

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

自分はleetcodeで用意されたmethod以外をコードで書くときはPEPに従ってsnake caseで書いています...

@TORUS0818
Copy link

拝見しました。良いと思いました。

余裕があれば、loopやinorder-treeの解き方も試してみると良いと思います。

def build_bst(left, right):
if left >= right:
return None
mid = (right + left) // 2

Choose a reason for hiding this comment

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

ここ以外の処理ではleft rightの順番となっております。
例えば引数であったり、nodeの処理部分
なので書き方を統一したらいいかと思いました。
ex) mid = (left + right) // 2

@@ -0,0 +1,30 @@
"""
Stack overflowしないかの一応の考察, height-balancedなので偏りがなく, 木の高さはlogn程度なので再帰の呼び出しは大丈夫そう
Copy link

Choose a reason for hiding this comment

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

一応、具体的な数字にしておくことをおすすめします。
Python の再帰の深さは限界いくらくらいで、n は今回いくつと考えているので、log n がいくつくらいになるのか、まで。
最後は、常に具体的な数字が問題になるので。(普段、わざわざ書くかどうかはともかく、練習ならば書いてもいいでしょう。)

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.

7 participants