Check for continuous binary tree in c++
C++ program for Check for continuous binary tree. Here more information.
// Include header file
#include <iostream>
using namespace std;
/*
C++ program for
Check if binary tree is continuous tree
Using recursion
*/
// Binary Tree Node
class TreeNode
{
public:
int data;
TreeNode *left;
TreeNode *right;
TreeNode(int data)
{
// Set node value
this->data = data;
this->left = nullptr;
this->right = nullptr;
}
};
class BinaryTree
{
public:
TreeNode *root;
BinaryTree()
{
this->root = nullptr;
}
int absValue(int num)
{
if (num < 0)
{
return -num;
}
return num;
}
// Check tree is continuous or not
bool isContinuous(TreeNode *node)
{
if (node != nullptr)
{
if ((node->left != nullptr &&
this->absValue(node->data - node->left->data) != 1) ||
(node->right != nullptr &&
this->absValue(node->data - node->right->data) != 1))
{
// Case
// When fail continuous tree rule
return false;
}
if (this->isContinuous(node->left) &&
this->isContinuous(node->right))
{
return true;
}
// When node value is not satisfied
// continuous tree properties
return false;
}
return true;
}
};
int main()
{
// Create new tree
BinaryTree *tree = new BinaryTree();
/*
Binary Tree
------------
5
/ \
4 4
/ / \
3 5 3
\
2
*/
// Add tree node
tree->root = new TreeNode(5);
tree->root->left = new TreeNode(4);
tree->root->right = new TreeNode(4);
tree->root->left->left = new TreeNode(3);
tree->root->right->right = new TreeNode(3);
tree->root->right->left = new TreeNode(5);
tree->root->left->left->right = new TreeNode(2);
if (tree->isContinuous(tree->root) == true)
{
cout << "Continuous Tree " << endl;
}
else
{
cout << "Not Continuous Tree " << endl;
}
// Case 2
/*
5
/ \
4 4
/ / \
3 5 3
\
1 <--- change value
*/
tree->root->left->left->right->data = 1;
if (tree->isContinuous(tree->root) == true)
{
cout << "Continuous Tree " << endl;
}
else
{
cout << "Not Continuous Tree " << endl;
}
return 0;
}
Output
Continuous Tree
Not Continuous Tree
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment