Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

largest complete subtree in a binary tree

Tags:

algorithm

I am defining a complete subtree as a tree with all levels full and the last level left justified i.e. all nodes are as far left as possible, and I want to find the largest subtree in a tree that is complete.

One method is to do the method outlined here for every node as root, which would take O(n^2) time.

Is there a better approach?

like image 768
suyash Avatar asked Nov 21 '15 10:11

suyash


People also ask

Where is the largest binary search subtree?

Start from root and do an inorder traversal of the tree. For each node N, check whether the subtree rooted with N is BST or not. If BST, then return size of the subtree rooted with N. Else, recur down the left and right subtrees and return the maximum of values returned by left and right subtrees.

Is a subtree in the larger tree?

A sub-tree is a tree itself that is the subset of a bigger binary tree. A subtree of a node means that it is the child of that node.

What is a complete subtree?

Structurally, a complete binary tree consists of either a single node (a leaf) or a root node with a left and right subtree, each of which is itself either a leaf or a root node with two subtrees. The set of all nodes underneath a particular node x is called the subtree rooted at x.


1 Answers

Since there isn't a C++ solution above, I have added my solution. Let me know if you feel there is anything incorrect or any improvements that can be made.

struct CompleteStatusWithHeight {
 bool isComplete;
 int height;
};

int FindLargestCompletetSubTreeSize(const unique_ptr<BinaryTreeNode<int>>& tree)
{
  return CheckComplete(tree).height;
}

CompleteStatusWithHeight CheckComplete(const unique_ptr<BinaryTreeNode<int>>& tree)
{
if (tree == nullptr) {
       return {true, -1};  // Base case.
}

auto left_result = CheckComplete(tree->left);
if (!left_result.isComplete) {
  return {false, 0};  // Left subtree is not balanced.
}
auto right_result = CheckComplete(tree->right);
if (!right_result.isComplete) {
  return {false, 0};  // Right subtree is not balanced.
}

bool is_balanced = abs(left_result.height - right_result.height) == 0;
bool is_left_aligned = (left_result.height - right_result.height) == 1;
bool is_leaf =  left_result.height  == -1 && right_result.height ==-1;
bool is_complete = is_balanced || is_left_aligned || is_leaf;

int height = max(left_result.height, right_result.height) + 1;
return {is_complete, height};
}
like image 152
Abhi Avatar answered Sep 29 '22 02:09

Abhi