Medium 333题 Largest BST Subtree

来源:互联网 发布:unity3d 物体穿过地面 编辑:程序博客网 时间:2024/05/20 07:37

Question:

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:

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

TLE方案

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int size=0;    public int largestBSTSubtree(TreeNode root) {        if(root==null) return size;        int size=0;        largestBSTSubtree(root,size);        return size;    }    public void largestBSTSubtree(TreeNode root, int size){        while(root!=null){            size++;            if(root.left!=null){                if(root.left.val>=root.val){                    size=0;                    largestBSTSubtree(root.right,size);                                    }                else                    largestBSTSubtree(root.left,size);            }            if(root.right!=null){                if(root.right.val<=root.val){                    size=0;                    largestBSTSubtree(root.left,size);                                    }                else                    largestBSTSubtree(root.right,size);            }        }    }}
还要再看。。。


0 0
原创粉丝点击