LeetCode-Largest BST Subtree
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.
Note:
A subtree must include all of its descendants.
Here's an example:
10 / \ 5 15 / \ \ 1 8 7
The Largest BST Subtree in this case is the highlighted one.
The return value is the subtree's size, which is 3.
Solution:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public class Result { 12 int min; 13 int max; 14 boolean isBST; 15 int maxBSTNodeNum; 16 public Result(int i, int x, boolean bst, int num){ 17 min = i; 18 max = x; 19 isBST = bst; 20 maxBSTNodeNum = num; 21 } 22 } 23 public int largestBSTSubtree(TreeNode root) { 24 if (root==null) return 0; 25 26 Result res = largestBSTSubtreeRecur(root); 27 return res.maxBSTNodeNum; 28 29 } 30 31 public Result largestBSTSubtreeRecur(TreeNode cur){ 32 boolean isBST = true; 33 int min = cur.val; 34 int max = cur.val; 35 int nodeNum = 1; 36 int subBSTNodeNum = 0; 37 38 Result leftRes=null, rightRes=null; 39 if (cur.left!=null){ 40 leftRes = largestBSTSubtreeRecur(cur.left); 41 if (!leftRes.isBST) isBST = false; 42 else { 43 if (leftRes.max>=cur.val) isBST = false; 44 else { 45 min = leftRes.min; 46 } 47 } 48 if (isBST) subBSTNodeNum += leftRes.maxBSTNodeNum; 49 } 50 51 if (cur.right!=null){ 52 rightRes = largestBSTSubtreeRecur(cur.right); 53 if (!rightRes.isBST) isBST = false; 54 else { 55 if (rightRes.min<=cur.val) isBST = false; 56 else { 57 max = rightRes.max; 58 } 59 } 60 if (isBST) subBSTNodeNum += rightRes.maxBSTNodeNum; 61 } 62 63 if (isBST) nodeNum = subBSTNodeNum+1; 64 else { 65 if (leftRes!=null) nodeNum = Math.max(nodeNum,leftRes.maxBSTNodeNum); 66 if (rightRes!=null) nodeNum = Math.max(nodeNum,rightRes.maxBSTNodeNum); 67 } 68 69 return new Result(min,max,isBST,nodeNum); 70 } 71 }