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.
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?
Solutionpublic class Solution { public int largestBSTSubtree(TreeNode root) { if (root == null) return 0; if (isValidBST(root)) return largestBSTSubtree(root.left)+largestBSTSubtree(root.right)+1; else return Math.max(largestBSTSubtree(root.left), largestBSTSubtree(root.right)); } public boolean isValidBST(TreeNode root) { if (root == null) return true; return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE); } public boolean dfs(TreeNode root, long min, long max) { if (root == null) return true; if (root.val <= min || root.val >= max) return false; return dfs(root.left, min, root.val) && dfs(root.right, root.val, max); } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/65189.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...
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); ...
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...
Problem Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node c...
阅读 1712·2021-11-24 10:18
阅读 2157·2021-11-18 13:20
阅读 2313·2021-08-23 09:46
阅读 940·2019-08-30 15:56
阅读 2815·2019-08-30 15:53
阅读 717·2019-08-30 14:22
阅读 454·2019-08-29 15:34
阅读 2507·2019-08-29 12:14