Dashboard Temp Share Shortlinks Frames API

HTMLify

day34.py
Views: 4 | Author: prakhardoneria
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
    def largestBst(self, root):
        self.max_size = 0
        
        def traverse(node):
            if not node:
                return True, 0, float('inf'), float('-inf')
            
            left_is_bst, left_size, left_min, left_max = traverse(node.left)
            right_is_bst, right_size, right_min, right_max = traverse(node.right)
            
            if left_is_bst and right_is_bst and left_max < node.data < right_min:
                curr_size = 1 + left_size + right_size
                self.max_size = max(self.max_size, curr_size)
                
                curr_min = min(node.data, left_min)
                curr_max = max(node.data, right_max)
                
                return True, curr_size, curr_min, curr_max
            
            return False, 0, 0, 0
            
        traverse(root)
        return self.max_size