333. 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.
分析:http://www.cnblogs.com/grandyang/p/5188938.html
这道题让我们求一棵二分树的最大二分搜索子树,所谓二分搜索树就是满足左<根<右的二分树,我们需要返回这个二分搜索子树的节点个数。题目中给的提示说我们可以用之前那道Validate Binary Search Tree的方法来做,时间复杂度为O(nlogn),这种方法是把每个节点都当做根节点,来验证其是否是二叉搜索数,并记录节点的个数,若是二叉搜索树,就更新最终结果,参见代码如下:
1 int largestBSTSubtree(TreeNode root) { 2 int[] res = new int[1]; 3 helper(root, res); 4 return res[0]; 5 } 6 void helper(TreeNode root, int[] res) { // assume eacho node is the root 7 if (root == null) return; 8 int d = count(root, Integer.MIN_VALUE, Integer.MAX_VALUE); 9 res[0] = Math.max(res[0], d); 10 helper(root.left, res); 11 helper(root.right, res); 12 } 13 14 int count(TreeNode root, int mn, int mx) { // check whether it is a BST, if no, return -1, if yes, return its # of nodes. 15 if (root == null) return 0; 16 if (root.val < mn || root.val > mx) return -1; 17 int left = count(root.left, mn, root.val); 18 if (left == -1) return -1; 19 int right = count(root.right, root.val, mx); 20 if (right == -1) return -1; 21 return left + right + 1; 22 }
O(n)
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 int largestBSTSubtree(TreeNode root) { 12 int[] res = new int[1]; 13 largestBSTHelper(root, res); 14 return res[0]; 15 } 16 17 private Data largestBSTHelper(TreeNode root, int[] res) { 18 Data curr = new Data(); 19 if (root == null) { 20 curr.isBST = true;
return curr; 23 } 24 25 Data left = largestBSTHelper(root.left, res); 26 Data right = largestBSTHelper(root.right, res); 27 if (left.isBST && root.val > left.max && right.isBST && root.val < right.min) { 28 curr.isBST = true; 29 curr.size = 1 + left.size + right.size; 30 curr.min = Math.min(root.val, left.min); 31 curr.max = Math.max(root.val, right.max); 32 res[0] = Math.max(res[0], curr.size); 33 }
return curr; 37 } 38 } 39 40 class Data { 41 boolean isBST = false; 42 // the minimum for right sub tree or the maximum for right sub tree 43 int min = Integer.MAX_VALUE; 44 int max = Integer.MIN_VALUE; 45 // if the tree is BST, size is the size of the tree; otherwise zero 46 int size = 0; 47 }
http://blog.csdn.net/likecool21/article/details/44080779