原题链接在这里:https://leetcode.com/problems/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.
Follow up:
Can you figure out ways to solve it with O(n) time complexity?
题解:
采用bottom-up的方法,简历新的class, 用来存储
- 当前节点为root的subtree是否是BST
- 若是,最小val 和最大val.
- size是当前subtree的大小.
然后从下到上更新,若是中间过程中size 比 res大,就更新res.
Time Complexity: O(n). 每个点不会访问超过两遍. Space: O(logn). Recursion stack space.
AC Java:
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 = {0}; 13 helper(root, res); 14 return res[0]; 15 } 16 17 private Node helper(TreeNode root, int [] res){ 18 Node cur = new Node(); 19 if(root == null){ 20 cur.isBST = true; 21 return cur; 22 } 23 Node left = helper(root.left, res); 24 Node right = helper(root.right, res); 25 if(left.isBST && root.val > left.max && right.isBST && root.val < right.min){ 26 cur.isBST = true; 27 cur.min = Math.min(root.val, left.min); 28 cur.max = Math.max(root.val, right.max); 29 cur.size = left.size + right.size + 1; 30 if(cur.size > res[0]){ 31 res[0] = cur.size; 32 } 33 } 34 return cur; 35 } 36 } 37 38 class Node{ 39 boolean isBST; 40 int min; 41 int max; 42 int size; 43 public Node(){ 44 isBST = false; 45 min = Integer.MAX_VALUE; 46 max = Integer.MIN_VALUE; 47 size = 0; 48 } 49 }