Coding problem
Is it a valid search tree?
The task
A product catalogue keeps its prices in a binary search tree, and a bug report says some inserts broke it.
Complete IsSearchTree(TreeNode? root). Return true if, for every node, all values in its left subtree are smaller than the node's value and all values in its right subtree are larger. Duplicates are not allowed. An empty tree (null) is valid. The TreeNode class is given; do not change it.
Signature
public static bool IsSearchTree(TreeNode? root)
Examples
- tree
[5, 3, 8, 1, 4, 7, 9]→true. Every node is between the limits set by the nodes above it. - tree
[5, 3, 8, 1, 6]→false. 6 is larger than its parent 3 but sits in 5's left subtree, where every value must be below 5.
Limits: Up to 5,000 nodes. Trees are written level by level, with null for a missing child.
The tests check: an empty tree, one node, a duplicate, values on the wrong side of a grandparent (left and right), int.MinValue and int.MaxValue as values, and a chain of 2,000 nodes.
Hints
Your code
Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;
// A node of a binary tree. Do not change this class: the tests build trees with it.
public sealed class TreeNode
{
public int Val;
public TreeNode? Left;
public TreeNode? Right;
public TreeNode(int val, TreeNode? left = null, TreeNode? right = null)
{
Val = val;
Left = left;
Right = right;
}
}
public static class Solution
{
// Returns true when every left subtree holds only smaller values and every right subtree only larger ones.
public static bool IsSearchTree(TreeNode? root)
{
throw new NotImplementedException();
}
}This problem comes with TechInterviewNotes Full Access
Unlock all paid content on TechInterviewNotes.