I was trying to find the Maximum sum BST of a binary tree on LeetCode. While the Java code I have come up with, mostly seems right and is able to pass 55 out of the given 59 test cases too, the error of 'Time Limit Exceeded' comes up.
Is there anything I can change, in the same given code, that would optimize it and/or get it accepted?
problem statement
1373. Maximum Sum BST in Binary Tree
Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a 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
Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
Output: 20
Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.Constraints:
The number of nodes in the tree is in the range [1, 4 * 10⁴].
-4 * 1e⁴ <= Node.val <= 4 * 1e⁴
The contest calls Solution.maxSumBST()
class Solution { int maxSum = 0; int sum = 0; TreeNode ansNode = new TreeNode(); private boolean isBST(TreeNode root, int minVal, int maxVal) { //To check if a tree is a BST if (root==null) { return true; } if (root.val>=maxVal || root.val<=minVal) { return false; } return (isBST(root.left, minVal, root.val) && isBST(root.right, root.val, maxVal)); } private void rootFinder(TreeNode root) { //Helper function to find the root of the required BST if (root==null) { return; } rootFinder(root.left); if (isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE)) { int currSum = sumFinder(root); if (currSum > maxSum) { maxSum = currSum; ansNode = root; } sum = 0; } rootFinder(root.right); } public int maxSumBST(TreeNode root) { rootFinder(root); return maxSum; } private int sumFinder (TreeNode root) { //To find the sum of all the nodes of a tree if (root==null) { return 0; } sumFinder(root.left); sum = sum + root.val; sumFinder(root.right); return sum; } }