333 Largest BST Subtree

1. 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.

Follow up: Can you figure out ways to solve it with O(n) time complexity?

2. Implementation

(1) Post-order Traversal

思路: 在后序遍历的过程中利用validate binary search tree的思想,对每个node的值,与它的leftSubTree最大值和rightSubtree最小值比较,如果node.val 小于等于leftSubTree的最大值或者大于等于rightSubTree的最小值,或者树的size是-1,则以该node作为root构成的树不是binary search tree. 然后每个node遍历完后返回一个数组,其中数组第一个元素存储的是以该node作为树的最小值,第二个元素存储的是以该node作为树最大值,第三个元素存储的是树的size。

3. Time & Space Complexity

Post-order Traversal: 时间复杂度: O(n), 空间复杂度: O(h)

Last updated

Was this helpful?