/
Leetcode 98 Validate Binary search tree - July 25 2018.cs
60 lines (51 loc) · 1.74 KB
/
Leetcode 98 Validate Binary search tree - July 25 2018.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Leetcode_98_Validate_binary_search_tree
{
/// <summary>
/// Leetcode 98 - validate binary search tree
/// code review 7/25/2018
/// </summary>
class Program
{
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
static void Main(string[] args)
{
}
public bool IsValidBST(TreeNode root)
{
return checkBSTValidWithRange(root, long.MinValue, long.MaxValue);
}
/// <summary>
/// By giving range minimum and maximum, the tree is also forced to give
/// left child smaller than parent node, right child bigger than parent node
/// </summary>
/// <param name="node"></param>
/// <param name="rangeMin"></param>
/// <param name="rangeMax"></param>
/// <returns></returns>
private static bool checkBSTValidWithRange(TreeNode node, long rangeMin, long rangeMax)
{
if (node == null)
return true;
var current = node.val;
if (current <= rangeMin || current >= rangeMax) // bug catched: = should be included
return false;
var checkLeftSubTree = checkBSTValidWithRange(node.left, rangeMin, current);
if (!checkLeftSubTree)
return false;
var checkRightSubtree = checkBSTValidWithRange(node.right, current, rangeMax);
if (!checkRightSubtree)
return false;
return true;
}
}
}