forked from xieqilu/Qilu-leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path31.ValidateBST.cs
84 lines (75 loc) · 2.53 KB
/
31.ValidateBST.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//determine if a binary tree is a binary search tree.
using System;
namespace DeterminBST
{
public class TreeNode
{
public TreeNode left{ get; set;}
public TreeNode right{ get; set;}
public int val{ get; private set;}
public TreeNode(int val)
{
this.val = val;
this.left = null;
this.right = null;
}
}
public class Solution1 {
//private object prev;
public static bool IsValidBST(TreeNode root) {
if(root==null)
return true;
//Note: do not use Int32.MinValue, because the value of node could be Int32.MinValue also!!!
//Instead, use an object to box the int value. Then we can use null to distinguish the initial value.
object prev=null;
return IsValidBSTHelper(root,ref prev);
}
private static bool IsValidBSTHelper(TreeNode root,ref object prev){ //Note: must pass by reference to make prev consistant
if(root == null) return true; //null is a valid BST
if(IsValidBSTHelper(root.left,ref prev)){
if(prev==null || root.val>(int)prev){ //unbox prev to get its int value
prev = root.val;
return IsValidBSTHelper(root.right,ref prev);
}
return false;
}
return false;
}
}
public class Solution2 {
public static bool IsValidBST(TreeNode root) {
//Do not use Int32.MaxValue and Int32.MinValue, becasue the value of tree node may be these two values too.
//Instead use object to box int value and pass two null objects as initial value.
return IsValidBSTHelper(root, null, null);
}
private static bool IsValidBSTHelper(TreeNode p, object low, object high) {
if (p == null) return true;
return (low == null || p.val > (int)low) && (high == null || p.val < (int)high) //unbox object when comparing value
&& IsValidBSTHelper(p.left, low, (object)p.val) //box int and pass the object
&& IsValidBSTHelper(p.right, (object)p.val, high); //box int and pass the object
}
}
class MainClass
{
public static void Main (string[] args)
{
//construct a binary search tree
TreeNode root = new TreeNode (5);
TreeNode nodeA = new TreeNode (3);
TreeNode nodeB = new TreeNode (6);
TreeNode nodeC = new TreeNode (7);
TreeNode nodeD = new TreeNode (8);
TreeNode nodeE = new TreeNode (4);
TreeNode nodeF = new TreeNode (2);
root.left = nodeA;
root.right = nodeC;
nodeA.left = nodeF;
nodeA.right = nodeE;
nodeC.left = nodeB;
nodeC.right = nodeD;
//The two solutions are already tested by all Leetcode test cases!!!
Console.WriteLine(Solution1.IsValidBST(root));//true
Console.WriteLine (Solution2.IsValidBST (root)); //true
}
}
}