Convert Sorted Array to Binary Search Tree
LeetCode 108 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Root = middle element; recurse on halves.
நான் Convert Sorted Array to Binary Search Tree (LeetCode 108) ஐ இப்படித் தீர்த்தேன் — BST பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
The middle element of a sorted array is a perfect root: half the values go left, half go right. Recurse on each half and the tree stays height-balanced.
Approach
- 1
traverse(start, end): empty range → None.
- 2
mid = (start + end) // 2 becomes the node.
- 3
Left subtree from [start, mid−1], right from [mid+1, end].
நான் எப்படித் தீர்த்தேன்
Divide by the middlePythonO(n) time
class Solution:
def sortedArrayToBST(self, nums):
def traverse(inorder, inStart, inEnd):
if inStart > inEnd:
return None
mid = (inStart + inEnd) // 2
root = TreeNode(inorder[mid])
root.left = traverse(inorder, inStart, mid - 1)
root.right = traverse(inorder, mid + 1, inEnd)
return root
return traverse(nums, 0, len(nums) - 1)Convert Sorted Array to Binary Search Tree — அடிக்கடி கேட்கப்படும் கேள்விகள்
Convert Sorted Array to Binary Search Tree பின்னாலுள்ள intuition என்ன?
The middle element of a sorted array is a perfect root: half the values go left, half go right. Recurse on each half and the tree stays height-balanced.
Convert Sorted Array to Binary Search Tree (LeetCode 108) ஐ எப்படித் தீர்ப்பது?
1. traverse(start, end): empty range → None. 2. mid = (start + end) // 2 becomes the node. 3. Left subtree from [start, mid−1], right from [mid+1, end].
Convert Sorted Array to Binary Search Tree இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(log n) recursion. (Accepted approach: Divide by the middle.)
Convert Sorted Array to Binary Search Tree இல் பொதுவான தவறுகள் என்ன?
Either middle works for even lengths; the tests accept any balanced BST.