private BST reconstructBSTFromRange(int lowerIdx, int upperIdx, int[] preOrderTraversalValues, TreeInfoForRConstruct currentSubTreeInfo) { if (currentSubTreeInfo.RootIdx == preOrderTraversalValues.Length) { return(null); //This means we have finished all of the nodes } var rootValue = preOrderTraversalValues[currentSubTreeInfo.RootIdx]; if (rootValue < lowerIdx || rootValue >= upperIdx) { return(null); // This node is not valid to be added. Also take care of duplicates } currentSubTreeInfo.RootIdx += 1; var leftSubtree = reconstructBSTFromRange(lowerIdx, rootValue, preOrderTraversalValues, currentSubTreeInfo); var rightSubtree = reconstructBSTFromRange(rootValue, upperIdx, preOrderTraversalValues, currentSubTreeInfo); var newBST = new BST(rootValue); newBST.left = leftSubtree; newBST.right = rightSubtree; return(newBST); }
public ClosestValueInBST() { int target = 12; //BST l = new BST(34); //l.left = new BST(21); //l.left.left = new BST(19); BST left = new BST(5) { left = new BST(2), right = new BST(6), value = 5 }; BST right = new BST(15) { left = new BST(13), right = new BST(22), value = 15 }; BST tree = new BST(10) { left = left, right = right, value = 10 }; var closest = FindClosestValueInBst(tree, target, tree.value); Console.WriteLine($"Closest number to {target} in tree is {closest}"); }
public int FindClosestValueInBst(BST tree, int target) { return(FindClosestValueInBst(tree, target, tree.value)); }
public bool ValidateBst(BST tree) { return(isValidateHelper(tree, int.MinValue, int.MaxValue)); }