#include <bits/stdc++.h>
using namespace std;
// tree node is defined
class TreeNode
{
public:
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int data)
{
val = data;
left = NULL;
right = NULL;
}
};
// recursive function to check if there is a dead end
// return true if there is no dead end
// return false if there is dead end
bool isAnyDeadEndRecur(TreeNode *root, int range_min, int range_max)
{
// base case
// if root is NULL, no dead end
if (!root)
return true;
// invalid range so no further insertion possible
// there is a dead end
if (range_min >= range_max)
return false;
return isAnyDeadEndRecur(root->left, range_min, root->val - 1) && isAnyDeadEndRecur(root->right, root->val + 1, range_max);
}
// function to check if there is a dead end
// returns true if there is a dead end
// returns false if there is no dead end
bool isAnyDeadEnd(TreeNode *root)
{
// initially, the range is [INT_MIN, INT_MAX]
// retuned negation of the result from the recursive function
return !isAnyDeadEndRecur(root, INT_MIN, INT_MAX);
}
int main()
{
// tree same as the 1st example
TreeNode *root1 = new TreeNode(6);
root1->left = new TreeNode(4);
root1->right = new TreeNode(12);
root1->left->left = new TreeNode(3);
root1->left->left->left = new TreeNode(2);
root1->left->right = new TreeNode(5);
root1->right = new TreeNode(12);
root1->right->left = new TreeNode(11);
root1->right = new TreeNode(15);
bool result = isAnyDeadEnd(root1);
if (result)
{
cout << "There is dead end in the BST\n";
}
else
{
cout << "There is no dead end in the BST\n";
}
// tree same as the 2nd example
TreeNode *root2 = new TreeNode(16);
root2->left = new TreeNode(3);
root2->left->right = new TreeNode(13);
root2->left->right->left = new TreeNode(10);
root2->right = new TreeNode(20);
root2->right->left = new TreeNode(18);
result = isAnyDeadEnd(root2);
if (result)
{
cout << "There is dead end in the BST\n";
}
else
{
cout << "There is no dead end in the BST\n";
}
return 0;
}
Output
There is dead end in the BST
There is no dead end in the BST
0 Comments