您的位置:首页 > 其它

333. Largest BST Subtree

2017-03-25 22:33 323 查看
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.

Hint:
You can recursively use algorithm similar to 98.
Validate Binary Search Tree at each node of the tree, which will result in O(nlogn) time complexity.

Follow up:

Can you figure out ways to solve it with O(n) time complexity?

Solution:

At first I was thinking using in order traversal, marked out the possible start and end so we just need to find the longest increasing sequence between the a possible start and a possible end. But the thing is how to know which node is a possible start and
which node is a possible end.

But it is too hard to figure out the right start and right end.

For example the in order traversal is 42135, but 135 is not the right start and end, so we also need to record the level and it is too complex, however I believe this problem can be solved with in order traversal.

Another thinking way is Divide and conquer, for the left and right subtree, get the max number of the subtree and whether it is the root of that subtree. If one of them are not the root, the whole subtree will not be a BST so just return the max of left
and right subtree, otherwise check the min, max and root.val to see whether this subtree is a BST.

Code:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
class Result{
int min;
int max;
int num;
boolean isRoot;
Result(int min, int max, int num, boolean isRoot){
this.min = min;
this.max = max;
this.num = num;
this.isRoot = isRoot;
}
}

public int largestBSTSubtree(TreeNode root) {
return helper(root).num;
}

Result helper(TreeNode root){
if(root == null) return new Result(Integer.MAX_VALUE,Integer.MIN_VALUE,0,true);
Result l = helper(root.left);
Result r = helper(root.right);
if(l.isRoot && r.isRoot){
if(root.val > l.max && root.val < r.min){
return new Result(Math.min(root.val,l.min), Math.max(root.val,r.max), 1 + r.num + l.num, true);
}
}
return new Result(0,0,Math.max(l.num,r.num),false);
}
}

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: