/** 333.Largest BST subtree * 2016-3-27 by Mingyang * This topic my train of thought, the bottom-up method is very correct! However, the unique point of this topic is that for a * tree is not a BST judgment, he must show that the largest Zuozi, the smallest of the right subtree is smaller, so it seems to be * must ensure that root must save the current subtree 1.isbst?2.left smallest .3.right Biggest.4.node Number * You can build a class first, or you can make an array*/ Public intlargestbstsubtree (TreeNode root) {if(Root = =NULL)return0; int[] ret =DFS1 (root); returnRet[3]; } Private int[] DFS1 (TreeNode node) {int[] L =New int[]{1, Node.val, Node.val, 0};//isbst, Min, Max, Numnodesbst int[] r =New int[]{1, Node.val, Node.val, 0 }; if(Node.left! =NULL) L =DFS1 (Node.left); if(Node.right! =NULL) R =DFS1 (node.right); BooleanIsbst = l[0] = = 1 && r[0] = = 1 && node.val >= l[2] && node.val <= r[1]; intNumbstnodes = Isbst? 1 + l[3] + r[3]: Math.max (l[3], r[3] ); return New int[]{Isbst 1:0, l[1], r[2], numbstnodes}; }
333.Largest BST Subtree