-
Notifications
You must be signed in to change notification settings - Fork 0
108. Convert Sorted Array to Binary Search Tree #24
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
base: main
Are you sure you want to change the base?
Conversation
root = TreeNode(nums[middle_index]) | ||
root.left = self.sortedArrayToBST(nums[:middle_index]) | ||
root.right = self.sortedArrayToBST(nums[middle_index+1:]) | ||
return root |
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.
読みやすいです。
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.
良いと思います 👍 Step 3の解法がシンプルで理解しやすかったです。
|
||
## 他の人のPRやコメントを踏まえて実装 | ||
leetcodeの解法 | ||
height-balancedだから空間計算量はO(logn)か |
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.
インデックスを用いる解法なら、PythonのList Slicingによるコピーが発生しないので、空間計算量はcall stack分のO(logn)になりそうですよね。
return result | ||
``` | ||
|
||
indexを狭めていく方式もある |
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.
step3 の nums 自体をスライスして渡す方と比べると、個人的には index を使ったこちらの方が好みですね。問題の条件によって選択できると良さそうです。
middle_index = len(nums) // 2 | ||
root = TreeNode(nums[middle_index]) | ||
root.left = self.sortedArrayToBST(nums[:middle_index]) | ||
root.right = self.sortedArrayToBST(nums[middle_index+1:]) |
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.
これイマイチ明記がなくいつも迷うのですが、インデックスは一応スペースを開けることが多いのではないかと思います (nums[middle_index + 1]
)。
問題:108. Convert Sorted Array to Binary Search Tree
次の問題:112. Path Sum