FastPrepSerialize a Binary Search Tree
Problem · Tree

Serialize a Binary Search Tree

Learn this problem
MediumConfluent logoConfluentFULLTIMEONSITE INTERVIEW

Problem statement

You are given the root of a binary search tree with unique integer values. Serialize the tree as its preorder traversal, joining decimal values with commas and using no null markers.

Return the empty string for an empty tree.

As an interview follow-up, explain how to deserialize this representation in linear time by consuming preorder values under valid lower and upper bounds, and how to produce the preorder iteratively for a very deep tree.

Function

serializeBST(root: TreeNode) → String

Examples

Example 1

root = [2,1,3]return = "2,1,3"

Preorder visits the root, then the left subtree, then the right subtree.

Example 2

root = [8,3,10,1,6,null,14,null,null,4,7,13]return = "8,3,1,6,4,7,10,14,13"

The output lists exactly the preorder traversal and does not emit null markers.

Example 3

root = []return = ""

An empty tree serializes to the empty string.

Constraints

  • The tree contains at most 100000 nodes.
  • -1000000000 <= node.val <= 1000000000.
  • All values are unique and satisfy the binary-search-tree invariant.

More Confluent problems

drafts saved locally
public String serializeBST(TreeNode root) {
    // Write your code here.
}
root[2,1,3]
expected"2,1,3"
checking account