Advertisement
Guest User

Untitled

a guest
Jan 28th, 2020
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.82 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  *     public int val;
  5.  *     public TreeNode left;
  6.  *     public TreeNode right;
  7.  *     public TreeNode(int x) { val = x; }
  8.  * }
  9.  */
  10. public class Solution {
  11.     public bool IsValidBST(TreeNode root) {
  12.        
  13.         int? current = null;
  14.         return IsValidBST(root, ref current);
  15.     }
  16.    
  17.     public bool IsValidBST(TreeNode node, ref int? current)
  18.     {        
  19.         if(node == null)
  20.             return true;
  21.        
  22.         if(!IsValidBST(node.left, ref current))
  23.             return false;
  24.        
  25.         if(current >= node.val)
  26.             return false;
  27.        
  28.         current = node.val;
  29.        
  30.         if(!IsValidBST(node.right, ref current))
  31.             return false;
  32.                
  33.         return true;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement