iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 53

[Day 53] Validate Binary Search Tree (Medium)

  • 分享至 

  • xImage
  •  

98. Validate Binary Search Tree

Solution 1: DFS

class Solution:
    def _isValidBST(self, root, minNode, maxNode):
        if not root:
            return True
        
        # 1. Not all the nodes in the left less than root
        # 2. Not all the nodes in the right greater than root
        if (maxNode and root.val >= maxNode.val) or (minNode and root.val <= minNode.val):
            return False
        else:
            isLftSubTreeValidBST = self._isValidBST(root.left, minNode, root)
            isRhtSubTreeValidBST = self._isValidBST(root.right, root, maxNode)
            return isLftSubTreeValidBST and isRhtSubTreeValidBST
    
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        return self._isValidBST(root, None, None)

Time Complexity: O(N)
Space Complexity: O(N) // The recursive call need O(N) stack in worst case

Solution 2: BFS (Level-Order)

Time Complexity: O(N)
Space Complexity: O(N)

Solution 3: Inorder Traverse

Time Complexity: O(N)
Space Complexity: O(N)

Reference

https://leetcode.com/problems/validate-binary-search-tree/discuss/32141/C%2B%2B-simple-recursive-solution
https://leetcode.com/problems/validate-binary-search-tree/discuss/32109/My-simple-Java-solution-in-3-lines
https://leetcode.com/problems/validate-binary-search-tree/discuss/32112/Learn-one-iterative-inorder-traversal-apply-it-to-multiple-tree-questions-(Java-Solution)
https://leetcode.com/problems/validate-binary-search-tree/discuss/32104/C%2B%2B-in-order-traversal-and-please-do-not-rely-on-buggy-INT_MAX-INT_MIN-solutions-any-more
https://leetcode.com/problems/validate-binary-search-tree/discuss/786520/General-Tree-Traversal-Problems-interview-Prep


上一篇
[Day 52] Linked List Cycle (Easy)
下一篇
[Day 54 - 1] Binary Tree Maximum Path Sum (Hard)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言