Problem : https://leetcode.com/problems/largest-bst-subtree/
To form a BST, the left sub-tree and right sub-tree are also need to be BST.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def largestBSTSubtree(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
self.result = 1
def postorder(node):
if node.left and node.right:
lmx, lmi, ltotal = postorder(node.left)
rmx, rmi, rtotal = postorder(node.right)
if ltotal < 0 or rtotal < 0:
return lmx, lmi, -1
if node.val <= lmx:
return lmx, lmi, -1
if node.val >= rmi:
return rmx, rmi, -1
self.result = max(self.result, 1 + ltotal + rtotal)
return rmx, lmi, 1 + ltotal + rtotal
if node.left:
lmx, lmi, ltotal = postorder(node.left)
if ltotal < 0 :
return lmx, lmi, -1
if node.val <= lmx:
return lmx, lmi, -1
self.result = max(self.result, 1 + ltotal)
return node.val, lmi, 1 + ltotal
if node.right:
rmx, rmi, rtotal = postorder(node.right)
if rtotal < 0:
return rmx, rmi, -1
if node.val >= rmi:
return rmx, rmi, -1
self.result = max(self.result, 1 + rtotal)
return rmx, node.val, 1 + rtotal
return node.val, node.val, 1
postorder(root)
return self.result
No comments:
Post a Comment