Find the largest subtree in a binary tree, And the subtree is a binary search tree.

Source: Internet
Author: User
Question

Find the largest subtree in a binary tree, which is a binary search tree. The largest subtree refers to the subtree with the largest number of nodes.

This topic is analyzed to find the largest subtree in a binary tree. The subtree must be a binary search tree (BST ). The sub-tree concept needs to be focused. A binary tree is shown below as an example.
         ____10____        /          \      __5_         15_     /    \           \     1     8           7

So should the largest subtree of the binary tree be BST be regarded as subtree (1) or subtree (2?

         ____ 10____        /           \      __5_          15     -------- subtree (1)     /    \     1     8 
      __5_     /    \               -------- subtree (2)     1     8 

According to the definition of a subtree in Wikipedia, the subtree of a binary tree T consists of a node of T and all its descendants. That is to say, in this question, subtree (2) is the correct answer, because subtree (1) does not contain node 7 and does not meet the definition of the subtree.

Basic solution-the most natural solution from top to bottom is to traverse all the nodes of the binary tree starting from the root node and determine whether the subtree with the current node as the root is BST. If yes, the BST with the root node is the largest BST. If not, recursively call the left and right subtree and return the subtree with more nodes.
Void maxsubtree (pnode root, Int & MAX, pnode & RET) {If (! Root) {max = 0; ret = root; return;} If (isbst (Root) {// the tree with root as the root node is BST, set the result to root and return the result. For this function, see the blog "determining whether a tree is a binary search tree" max = size (Root); ret = root; return;} int Lmax, rmax; pnode LRET, rret; maxsubtree (root-> left, Lmax, LRET); // find the largest subtree in the left subtree, maxsubtree (root-> right, rmax, rret ); // find the maximum subtree max = Lmax> rmax? Lmax: rmax; // sets the maximum number of nodes. ret = Lmax> rmax? LRET: rret; // The root node of the maximum subtree set to BST}

Optimization Method-bottom-up

Since the top-down method calls isbst each time to determine whether the subtree with the current node as the root node is a binary search tree, each call time is O (n ), in fact, there are some repeated judgments. If the bottom-up method is used, we have known whether the child tree with the bottom node is BST before determining whether the child tree with the root node is BST. Therefore, as long as the subtree with the bottom node as the root is not BST, the subtree with the above node as the root must not be BST.

The method for determining whether a tree is a BST is as follows:

1) The left and right subtree of each node is BST

2) The value of each node is greater than the maximum value of the Left subtree.

3) The value of each node is smaller than the minimum value of the right subtree.

Therefore, when we use the bottom-up method, we need to pass some information up, including the maximum and minimum values of the subtree and the size of the subtree. Apparently, the size of the tree is equal to the size of the Left subtree + the size of the right subtree + 1.

// Find the largest BST subtree in a binary tree.// If the subtree is a BST, return total number of nodes.// If the subtree is not a BST, -1 is returned.int findLargestBSTSubtree(BinaryTree *p, int &min, int &max,                   int &maxNodes, BinaryTree *& largestBST) {  if (!p) return 0;  bool isBST = true;  int leftNodes = findLargestBSTSubtree(p->left, min, max, maxNodes, largestBST);  int currMin = (leftNodes == 0) ? p->data : min;  if (leftNodes == -1 ||     (leftNodes != 0 && p->data <= max))    isBST = false;  int rightNodes = findLargestBSTSubtree(p->right, min, max, maxNodes, largestBST);  int currMax = (rightNodes == 0) ? p->data : max;  if (rightNodes == -1 ||     (rightNodes != 0 && p->data >= min))    isBST = false;  if (isBST) {    min = currMin;    max = currMax;    int totalNodes = leftNodes + rightNodes + 1;    if (totalNodes > maxNodes) {      maxNodes = totalNodes;      largestBST = p;    }    return totalNodes;  } else {    return -1;   // This subtree is not a BST  }} BinaryTree* findLargestBSTSubtree(BinaryTree *root) {  BinaryTree *largestBST = NULL;  int min, max;  int maxNodes = INT_MIN;  findLargestBSTSubtree(root, min, max, maxNodes, largestBST);  return largestBST;}
Reference http://www.leetcode.com/2010/11/largest-binary-search-tree-bst-in.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.