10 / 5 15 / 1 8 7 return 3
public class Solution { public int largestBSTSubtree(TreeNode root) { if(root == null) return 0; int[] res = recursive(root); return res[2]; } public int[] recursive(TreeNode root){ int[] res = new int[5]; // res[0] BST or Not? // res[1] total number nodes of subtree // res[2] max number of BST subtree // res[3] min // res[4] max res[0] = 1; res[3] = Integer.MAX_VALUE; res[4] = Integer.MIN_VALUE; if(root == null) return res; int[] resL = recursive(root.left); int[] resR = recursive(root.right); if(resL[0] == 0 || resR[0] == 0 || resL[4] >= root.val || resR[3] <= root.val) res[0] = 0; res[1] = resL[1] + resR[1] + 1; res[2] = (res[0] == 1) ? res[1]: Math.max(resL[2], resR[2]); res[3] = root.val < resL[3] ? root.val : resL[3]; res[4] = root.val > resR[4] ? root.val : resR[4]; return res; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/70080.html
摘要:復雜度思路考慮對于每一個節點來說,能組成的的。那么并且所以我們需要兩個返回值,一個是這個是不是,另一個是當前的能組成的最大的值。代碼這個能構成一個這個不能構成一個 LeetCode[333] Largest BST Subtree Given a binary tree, find the largest subtree which is a Binary SearchTree (B...
Problem 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 descen...
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 ...
Problem Given a Binary Search Tree (BST) with root node root, and a target value V, split the tree into two subtrees where one subtree has nodes that are all smaller or equal to the target value, whil...
閱讀 1186·2023-04-25 17:05
閱讀 3011·2021-11-19 09:40
閱讀 3545·2021-11-18 10:02
閱讀 1740·2021-09-23 11:45
閱讀 3023·2021-08-20 09:36
閱讀 2783·2021-08-13 15:07
閱讀 1133·2019-08-30 15:55
閱讀 2459·2019-08-30 14:11