Interview Query

Binary Tree Conversion

Start Timer

0:00:00

Upvote
3
Downvote
Save question
Mark as completed
View comments
Next question

Given a sorted list, create a function convert_to_bst that converts the list into a binary tree. convert_to_bst returns a TreeNode holding the root of the binary tree. A TreeNode is defined as the following:

from dataclasses import dataclass

class TreeNode:
    pass

@dataclass
class TreeNode:
    value: int
    left: TreeNode = None
    right: TreeNode = None

The output binary tree should be balanced, meaning the height difference between the left and right subtree of all the nodes should be at most one.

Example:

Input:

[1, 2, 3, 4, 5]

Output:

imageConverted Binary Tree.png

Note: The output in the test cases will return an in-order traversal of your tree.

.
.
.
.
.


Comments

Loading comments