The Wayback Machine - https://web.archive.org/web/20240612141128/https://www.geeksforgeeks.org/find-the-largest-subtree-in-a-tree-that-is-also-a-bst/
Open In App

Find the largest BST subtree in a given Binary Tree | Set 3

Last Updated : 19 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Largest BST in a Binary Tree | Set 3

Method 3 (Shorter, Smarter and More Efficient) 

In this section, a different O(n) solution is discussed. This solution is simpler than the solutions discussed in Set-1 and Set-2 and works in O(n) time. In this method, we do not need to check explicitly if the binary tree is BST. A Tree is BST if the following is true for every node x. 

1. The largest value in the left subtree (of x) is smaller than the value of x.
2. The smallest value in the right subtree (of x) is greater than the value of x.

So, we will just check if the largest value of the left subtree is less than the value of the root node and the smallest value of right subtree is greater than the value of root node.

We will use a array/list ans :

• ans[0]=minimum value
• ans[1]=maximum value
• ans[2]=size of current largest BST

Algorithm:

1. If root==None:
return INT_MAX,INT_MIN,0
2. If (root.left==None and root.right==None):
             return root.data,root.data,1
3. Initialize ans=[0,0,0]
4. Check if the largest value of the left subtree is less than the value of the root node and the smallest value of the right subtree is greater than the value of the root node, if this holds true, update the ans accordingly and return ans.
5. If 4 is false, we will assign values as IMIN,IMAX, max(left[2],right[2] and return ans.

C++14




// C++ program to find largest BST in a Binary Tree.
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
struct Node
{
    int data;
    struct Node* left;
    struct Node* right;
      Node(int val)
    {
          this->data = val;
          left = NULL;
          right = NULL;
    }
};
 
vector<int> largestBSTBT(Node* root)
{
    // Base cases : When tree is empty or it has one child.
    if (root == NULL)
        return {INT_MAX, INT_MIN, 0};
    if (root->left == NULL && root->right == NULL)
        return {root->data, root->data, 1};
 
    // Recur for left subtree and right subtrees
    vector<int> left = largestBSTBT(root->left);
    vector<int> right = largestBSTBT(root->right);
 
    // Create a return variable and initialize its size.
    vector<int> ans(3, 0);
 
    // If whole tree rooted under current root is BST.
    if ((left[1] < root->data) && (right[0] > root->data))
    {
        ans[0] = min(left[0], min(right[0], root->data));
        ans[1] = max(right[1], max(left[1], root->data));
        // Update answer for tree rooted under current 'root'
        ans[2] = 1 + left[2] + right[2];
        return ans;
    }
 
    // If whole tree is not BST, return maximum of left and right subtrees
    ans[0] = INT_MIN;
    ans[1] = INT_MAX;
    ans[2] = max(left[2], right[2]);
 
    return ans;
}
 
int largestBSTBTutil(Node *root)
{
      return largestBSTBT(root)[2];
}
 
// Driver Function
int main() {
 
    /* Let us construct the following Tree
        50
       /  \
      75  45
     /
    45 */
 
    struct Node *root = new Node(50);
    root->left = new Node(75);
    root->right = new Node(45);
    root->left->left = new Node(40);
    printf(" Size of the largest BST is %d\n", largestBSTBTutil(root));
    return 0;
}


Java




// Java program to find largest BST in a Binary Tree.
import java.util.*;
 
class Main {
    public static int[] largestBSTBT(Node root)
    {
        // Base cases : When tree is empty or it has one
        // child.
        if (root == null)
            return new int[] { Integer.MAX_VALUE,
                               Integer.MIN_VALUE, 0 };
        if (root.left == null && root.right == null)
            return new int[] { root.data, root.data, 1 };
 
        // Recur for left subtree and right subtrees
        int[] left = largestBSTBT(root.left);
        int[] right = largestBSTBT(root.right);
 
        // Create a return variable and initialize its size.
        int[] ans = new int[3];
 
        // If whole tree rooted under current root is BST.
        if ((left[1] < root.data)
            && (right[0] > root.data)) {
            ans[0] = Math.min(
                left[0], Math.min(right[0], root.data));
            ans[1] = Math.max(right[1],
                              Math.max(left[1], root.data));
 
            // Update answer for tree rooted under current
            // 'root'
            ans[2] = 1 + left[2] + right[2];
            return ans;
        }
 
        // If whole tree is not BST, return maximum of left
        // and right subtrees
        ans[0] = Integer.MIN_VALUE;
        ans[1] = Integer.MAX_VALUE;
        ans[2] = Math.max(left[2], right[2]);
 
        return ans;
    }
 
    public static int largestBSTBTutil(Node root)
    {
        return largestBSTBT(root)[2];
    }
 
    // Driver Function
    public static void main(String[] args)
    {
        /* Let us construct the following Tree
            50
           /  \
          75  45
         /
        45 */
        Node root = new Node(50);
        root.left = new Node(75);
        root.right = new Node(45);
        root.left.left = new Node(40);
        System.out.println("Size of the largest BST is "
                           + largestBSTBTutil(root));
    }
}
 
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
class Node {
    int data;
    Node left, right;
 
    Node(int val)
    {
        this.data = val;
        left = null;
        right = null;
    }
}
 
// This code is contributed by Tapesh (tapeshdua420)


Python3




#User function Template for python3
IMIN = -2147483648
IMAX = 2147483647
def largestBst(root):
        if root==None:
            return IMAX,IMIN,0
        if (root.left==None and root.right==None):
            return root.data,root.data,1
         
        left=largestBst(root.left)
        right=largestBst(root.right)
 
         
        ans=[0,0,0]
         
        if left[1]<root.data and right[0]>root.data:
            ans[0]=min(left[0],right[0],root.data)
            ans[1]=max(right[1],left[1],root.data)
            ans[2]=1+left[2]+right[2]
            return ans
 
        ans[0]=IMIN
        ans[1]=IMAX
        ans[2]=max(left[2],right[2])
        return ans
 
def largestBstUtil(root):
      # Return the size of the largest sub-tree which is also a BST
     return largestBst(root)[2]
     
#  Driver Code Starts
import sys
sys.setrecursionlimit(1000000)
from collections import deque
# Tree Node
class newNode:
    def __init__(self, val):
        self.right = None
        self.data = val
        self.left = None
 
# Driver Code
if __name__ == '__main__':
      
    """Let us construct the following Tree
        50
        / \
        75 45
    /
    40 """
    root = newNode(50)
    root.left = newNode(75)
    root.right = newNode(45)
    root.left.left = newNode(40)
    print("Size of the largest BST is",largestBstUtil(root))


C#




// C# program to find largest BST in a Binary Tree.
using System;
 
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
public class Node {
    public int data;
    public Node left, right;
 
    public Node(int val)
    {
        this.data = val;
        left = null;
        right = null;
    }
}
 
public class GFG {
    public static int[] largestBSTBT(Node root)
    {
        // Base cases : When tree is empty or it has one
        // child.
        if (root == null)
            return new int[] { int.MaxValue, int.MinValue,
                               0 };
        if (root.left == null && root.right == null)
            return new int[] { root.data, root.data, 1 };
 
        // Recur for left subtree and right subtrees
        int[] left = largestBSTBT(root.left);
        int[] right = largestBSTBT(root.right);
 
        // Create a return variable and initialize its size.
        int[] ans = new int[3];
 
        // If whole tree rooted under current root is BST.
        if ((left[1] < root.data)
            && (right[0] > root.data)) {
            ans[0] = Math.Min(
                left[0], Math.Min(right[0], root.data));
            ans[1] = Math.Max(right[1],
                              Math.Max(left[1], root.data));
 
            // Update answer for tree rooted under current
            // 'root'
            ans[2] = 1 + left[2] + right[2];
            return ans;
        }
 
        // If whole tree is not BST, return maximum of left
        // and right subtrees
        ans[0] = int.MinValue;
        ans[1] = int.MaxValue;
        ans[2] = Math.Max(left[2], right[2]);
 
        return ans;
    }
 
    public static int largestBSTBTutil(Node root)
    {
        return largestBSTBT(root)[2];
    }
 
    // Driver Function
    public static void Main(string[] args)
    {
        /* Let us construct the following Tree
            50
           /  \
          75  45
         /
        45 */
        Node root = new Node(50);
        root.left = new Node(75);
        root.right = new Node(45);
        root.left.left = new Node(40);
        Console.WriteLine("Size of the largest BST is "
                          + largestBSTBTutil(root));
    }
}
 
// This code is contributed by Tapesh (tapeshdua420)


Javascript




// JavaScript program for above approach
 
// A binary tree node has data,
// pointer to left child and a
// pointer to right child
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}
 
function largestBSTBT(root) {
    // Base cases : When tree is empty or it has one child.
    if (root == null) return [Number.MAX_VALUE, Number.MIN_VALUE, 0];
    if (root.left == null && root.right == null) return [root.data, root.data, 1];
 
    // Recur for left subtree and right subtrees
    let left = largestBSTBT(root.left);
    let right = largestBSTBT(root.right);
 
    // Create a return variable and initialize its size.
    let ans = [0, 0, 0];
 
    // If whole tree rooted under current root is BST.
    if (left[1] < root.data && right[0] > root.data) {
        ans[0] = Math.min(left[0], Math.min(right[0], root.data));
        ans[1] = Math.max(right[1], Math.max(left[1], root.data));
        // Update answer for tree rooted under current 'root'
        ans[2] = 1 + left[2] + right[2];
        return ans;
    }
 
    // If whole tree is not BST, return maximum of left and right subtrees
    ans[0] = Number.MIN_VALUE;
    ans[1] = Number.MAX_VALUE;
    ans[2] = Math.max(left[2], right[2]);
 
    return ans;
}
 
function largestBSTBTutil(root) {
    return largestBSTBT(root)[2];
}
 
// Driver Function
let root = new Node(50);
root.left = new Node(75);
root.right = new Node(45);
root.left.left = new Node(40);
console.log("Size of the largest BST is",largestBSTBTutil(root));
 
// This code is contributed by adityamaharshi21


Output

Size of the largest BST is 2

Time Complexity: O(n),
 Auxiliary Space: O(n)

Here n is the number of nodes in the given Binary Tree.  



Previous Article
Next Article

Similar Reads

Check if a Binary tree is Subtree of another Binary tree | Set 3
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree-T Tree-S 1 3 / \ / 2
15 min read
Check if a Binary Tree is subtree of another binary tree | Set 1
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree S 10 / \ 4 6 \ 30 Tr
12 min read
Check if a binary tree is subtree of another binary tree | Set 2
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.For example, in the following case, Tree1 i
28 min read
Find the largest Complete Subtree in a given Binary Tree
Given a Binary Tree, the task is to find the size of largest Complete sub-tree in the given Binary Tree. Complete Binary Tree - A Binary tree is Complete Binary Tree if all levels are completely filled except possibly the last level and the last level has all keys as left as possible. Note: All Perfect Binary Trees are Complete Binary tree but reve
17 min read
Find the largest Perfect Subtree in a given Binary Tree
Given a Binary Tree, the task is to find the size of largest Perfect sub-tree in the given Binary Tree. Perfect Binary Tree - A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are at the same level. Examples: Input: 1 / \ 2 3 / \ / 4 5 6 Output: Size : 3 Inorder Traversal : 4 2 5 The following sub-tre
12 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Count of nodes in given N-ary tree such that their subtree is a Binary Tree
Given an N-ary tree root, the task is to find the count of nodes such that their subtree is a binary tree. Example: Input: Tree in the image below Output: 11Explanation: The nodes such that there subtree is a binary tree are {2, 8, 10, 6, 7, 3, 1, 9, 5, 11, 12}. Input: Tree in the image below Output: 9 Approach: The given problem can be solved by u
11 min read
K'th Largest Element in BST when modification to BST is not allowed
Given a Binary Search Tree (BST) and a positive integer k, find the k'th largest element in the Binary Search Tree. For example, in the following BST, if k = 3, then output should be 14, and if k = 5, then output should be 10. We have discussed two methods in this post. The method 1 requires O(n) time. The method 2 takes O(h) time where h is height
22 min read
Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
Given a binary tree, the task is to print the maximum sum of nodes of a sub-tree which is also a Binary Search Tree.Examples: Input : 7 / \ 12 2 / \ \ 11 13 5 / / \ 2 1 38 Output:44 BST rooted under node 5 has the maximum sum 5 / \ 1 38 Input: 5 / \ 9 2 / \ 6 3 / \ 8 7 Output: 8 Here each leaf node represents a binary search tree also a BST with su
12 min read
Largest BST in a Binary Tree | Set 2
Given a Binary Tree, write a function that returns the size of the largest subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size of the whole tree. Examples:Input: 5 / \ 2 4 / \ 1 3 Output: 3 The following subtree is the maximum size BST subtree 2 / \ 1 3 Input: 50 / \ 30 60 / \ / \ 5 20 45 70 /
11 min read