|
| 1 | +/** |
| 2 | + * Given a binary tree, find the largest subtree which is a Binary Search Tree |
| 3 | + * (BST), where largest means subtree with largest number of nodes in it. |
| 4 | + * |
| 5 | + * Note: |
| 6 | + * A subtree must include all of its descendants. |
| 7 | + * |
| 8 | + * Example: |
| 9 | + * Input: [10,5,15,1,8,null,7] |
| 10 | + * |
| 11 | + * 10 |
| 12 | + * / \ |
| 13 | + * 5 15 |
| 14 | + * / \ \ |
| 15 | + * 1 8 7 |
| 16 | + * Output: 3 |
| 17 | + * Explanation: The Largest BST Subtree in this case is the highlighted one. |
| 18 | + * The return value is the subtree's size, which is 3. |
| 19 | + * |
| 20 | + * Follow up: |
| 21 | + * Can you figure out ways to solve it with O(n) time complexity? |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * Definition for a binary tree node. |
| 26 | + * public class TreeNode { |
| 27 | + * int val; |
| 28 | + * TreeNode left; |
| 29 | + * TreeNode right; |
| 30 | + * TreeNode(int x) { val = x; } |
| 31 | + * } |
| 32 | + */ |
| 33 | + |
| 34 | +public class LargestBSTSubtree333 { |
| 35 | + public int largestBSTSubtree(TreeNode root) { |
| 36 | + if (root == null) return 0; |
| 37 | + return helper(root)[0]; |
| 38 | + } |
| 39 | + |
| 40 | + public int[] helper(TreeNode root) { |
| 41 | + // 0 1 2 3 |
| 42 | + // {res, isBST(0/1), lower, upper} |
| 43 | + if (root == null) return null; |
| 44 | + |
| 45 | + int[] left = helper(root.left); |
| 46 | + int[] right = helper(root.right); |
| 47 | + |
| 48 | + if (left == null && right == null) { |
| 49 | + return new int[]{1, 1, root.val, root.val}; |
| 50 | + } else if (left == null) { |
| 51 | + boolean isBST = right[1] == 1 && root.val < right[2]; |
| 52 | + int res = right[0] + (isBST ? 1 : 0); |
| 53 | + int lower = isBST ? root.val : 0; |
| 54 | + int upper = isBST ? right[3] : 0; |
| 55 | + return new int[]{res, isBST ? 1 : 0, lower, upper}; |
| 56 | + } else if (right == null) { |
| 57 | + boolean isBST = left[1] == 1 && root.val > left[3]; |
| 58 | + int res = left[0] + (isBST ? 1 : 0); |
| 59 | + int lower = isBST ? left[2] : 0; |
| 60 | + int upper = isBST ? root.val : 0; |
| 61 | + return new int[]{res, isBST ? 1 : 0, lower, upper}; |
| 62 | + } else { |
| 63 | + boolean isBST = left[1] == 1 && right[1] == 1 && root.val > left[3] && root.val < right[2]; |
| 64 | + int res = isBST ? (left[0] + right[0] + 1) : Math.max(left[0], right[0]); |
| 65 | + int lower = isBST ? left[2] : 0; |
| 66 | + int upper = isBST ? right[3] : 0; |
| 67 | + return new int[]{res, isBST ? 1 : 0, lower, upper}; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments