forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Tree] add Solution to Validate Binary Search Tree
- Loading branch information
Yi Gu
committed
Jun 19, 2016
1 parent
50f7735
commit 68eb8ce
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/validate-binary-search-tree/ | ||
* Primary idea: Keep min to go right and keep max to go left | ||
* Time Complexity: O(n), Space Complexity: O(1) | ||
* | ||
* Definition for a binary tree node. | ||
* public class TreeNode { | ||
* public var val: Int | ||
* public var left: TreeNode? | ||
* public var right: TreeNode? | ||
* public init(_ val: Int) { | ||
* self.val = val | ||
* self.left = nil | ||
* self.right = nil | ||
* } | ||
* } | ||
*/ | ||
|
||
class ValidateBinarySearchTree { | ||
func isValidBST(root: TreeNode?) -> Bool { | ||
return _helper(root, nil, nil) | ||
} | ||
|
||
private func _helper(node: TreeNode?, _ min: Int?, _ max: Int?) -> Bool { | ||
guard let node = node else { | ||
return true | ||
} | ||
|
||
if min != nil && node.val <= min { | ||
return false | ||
} | ||
if max != nil && node.val >= max { | ||
return false | ||
} | ||
|
||
return _helper(node.left, min, node.val) && _helper(node.right, node.val, max) | ||
} | ||
} |