0109. Convert Sorted List to Binary Search Tree
Medium | Binary Search Tree + Inorder Traversal | 108 ms (99.14%), 25.4 MB (58.06%)
Last updated
Medium | Binary Search Tree + Inorder Traversal | 108 ms (99.14%), 25.4 MB (58.06%)
Last updated
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.
Inorder traversal of BST is an array sorted in ascending order.
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.