0109. Convert Sorted List to Binary Search Tree
Medium | Binary Search Tree + Inorder Traversal | 108 ms (99.14%), 25.4 MB (58.06%)
Source: LeetCode - Convert Sorted List to Binary Search Tree GitHub: Solution / Performance
Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differs by more than 1.
Constraints:
The number of nodes in
headis in the range[0, 2 * 10^4].-10^5 <= Node.val <= 10^5
Based on the above understanding, we could use two indexes "Start and End" to simulate inorder traversal recursively by the DFS method.
Besides, whenever we meet a left-child node, we record the current head node's value and then move the head node to the next node before finding the right-child node so that each node's value is assigned in an inorder traversal manner.
# pseudo code
mid = (start + end) // 2
leftNode = dfs(start, mid - 1)
val = head.val
head = head.next
rightNode = dfs(mid + 1, end)
node = TreNode(val, left, right)
return node
Last updated
Was this helpful?