1. 程式人生 > >[Swift]LeetCode98. 驗證二叉搜尋樹 | Validate Binary Search Tree

[Swift]LeetCode98. 驗證二叉搜尋樹 | Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Example 1:

Input:
    2
   / \
  1   3
Output: true

Example 2:

    5
   / \
  1   4
     / \
    3   6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
             is 5 but its right child's value is 4.

給定一個二叉樹,判斷其是否是一個有效的二叉搜尋樹。

假設一個二叉搜尋樹具有如下特徵:

  • 節點的左子樹只包含小於當前節點的數。
  • 節點的右子樹只包含大於當前節點的數。
  • 所有左子樹和右子樹自身必須也是二叉搜尋樹。

示例 1:

輸入:
    2
   / \
  1   3
輸出: true

示例 2:

輸入:
    5
   / \
  1   4
     / \
    3   6
輸出: false
解釋: 輸入為: [5,1,4,null,null,3,6]。
     根節點的值為 5 ,但是其右子節點值為 4 。

28ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func isValidBST(_ root: TreeNode?) -> Bool {
16         return isValidBSTRecursive(root, Int.min, Int.max)
17     }
18     
19     func isValidBSTRecursive(_ node: TreeNode?, _ min: Int, _ max: Int) -> Bool {
20         if let currentNode = node {
21             if currentNode.val < max && currentNode.val > min &&
22                 isValidBSTRecursive(currentNode.left, min, currentNode.val) &&
23                 isValidBSTRecursive(currentNode.right, currentNode.val, max) {
24                     return true
25             }   
26         } else {
27             return true
28         }
29         return false;
30     }
31 }

32ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15   func isValidBST(_ root: TreeNode?, _ lowerBound: Int? = nil, _ upperBound: Int? = nil) -> Bool {
16     guard let root = root else { return true }
17     if let upper = upperBound, root.val >= upper { return false }
18     if let lower = lowerBound, root.val <= lower { return false }
19     if let left = root.left, left.val >= root.val { return false }
20     if let right = root.right, right.val <= root.val { return false }
21     let leftUpperBound = upperBound.map { max($0, root.val) } ?? root.val
22     let rightLowerBound = lowerBound.map { min($0, root.val) } ?? root.val
23     return isValidBST(root.left, lowerBound, leftUpperBound) && isValidBST(root.right, rightLowerBound, upperBound)
24   }
25 }

36ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func isValidBST(_ root: TreeNode?) -> Bool {
16         if root == nil {return true}
17         var root = root
18         var stack = [TreeNode]()
19         var prev :TreeNode? = nil
20         while root != nil || !stack.isEmpty{
21             while root != nil {
22                 stack.append(root!)
23                 root = root?.left
24             }
25             root = stack.popLast()
26             if prev != nil && root!.val <= prev!.val {return false}
27             prev = root
28             root = root?.right
29             
30         }
31         return true
32     }
33 }

44ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func isValidBST(_ root: TreeNode?) -> Bool {
16         guard let root = root else {
17             return true
18         }
19         
20         return helper(root, Int.min, Int.max)
21         
22     }
23     
24     func helper(_ root: TreeNode?, _ min: Int, _ max: Int) -> Bool {
25         guard let root = root else {
26             return true
27         }
28         
29         if let leftVal = root.left?.val {
30             if leftVal >= root.val {
31                 return false
32             }
33         }
34         
35         if let rightVal = root.right?.val {
36             if rightVal <= root.val{
37                 return false
38             }
39         }
40         
41         if root.val <= min || root.val >= max {
42             return false
43         }
44 
45         return helper(root.left, min, root.val) && helper(root.right, root.val, max)
46     }
47 }

60ms

 1 class Solution {
 2     func isValidBST(_ root: TreeNode?) -> Bool {
 3         return _helper(root, nil ,nil)
 4     }
 5     
 6     private func _helper(_ node: TreeNode?, _ min: Int?, _ max: Int?) -> Bool {
 7       guard let node = node else {
 8         return true
 9       }
10       // 所有右子節點都必須大於根節點
11       if let min = min, node.val <= min {
12         return false
13       }
14       // 所有左子節點都必須小於根節點
15       if let max = max, node.val >= max {
16         return false
17       }
18 
19       return _helper(node.left, min, node.val) && _helper(node.right, node.val, max)
20     }
21 }

 64ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func isValidBST(_ root: TreeNode?) -> Bool {
16         return isValidBSTUtil(root, min: Int.min, max: Int.max)
17     }
18     
19     func isValidBSTUtil(_ node: TreeNode?, min: Int, max: Int) -> Bool {
20         guard let node = node else { return true }
21         guard node.val > min && node.val < max else { return false }
22         return isValidBSTUtil(node.left, min: min, max: node.val) && isValidBSTUtil(node.right, min: node.val, max: max) 
23     }
24 }

84ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14  /*
15  思路:
16  1.左邊子樹一定小於根節點的父節點,節點層級越高,數值越大
17  2.右邊子樹一定大約根節點的父節點,節點層級越高,數值越小
18   */
19 class Solution {
20     func isValidBST(_ root: TreeNode?) -> Bool {
21         return isValidBST(root, Int.min, Int.max)
22     }
23     
24     func isValidBST(_ root:TreeNode?, _ min:Int, _ max:Int) -> Bool {
25         if (root == nil) {
26             return true
27         }
28         
29         if (root?.val)! <= min || (root?.val)! >= max {
30             return false
31         }
32         
33         return isValidBST(root?.left, min, (root?.val)!) && isValidBST(root?.right, (root?.val)!, max)
34     }
35 }