DAA: Continuous Tree

Continuous Tree

A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1.

Input :          3

                    /   \

                   2    4

                  /  \     \

                 1   3   5

Output: "Yes"

 3->2->1 every two adjacent node's absolute difference is 1

 3->2->3 every two adjacent node's absolute difference is 1

 3->4->5 every two adjacent node's absolute difference is 1

Input:            7

                    /   \

                   5    8

                  /  \     \

                 6   4   10

Output: "No"

For solving this problem, the various corner cases are to be kept in mind.

  1. Empty tree
  2. Single node tree
  3. Node with only one left child
  4. Node with only one right child

Approach 1:

Recursively calculates if the left is right subtrees are continuous. During this check, we also see that if the difference between the current node key and the child key is one.

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 // Binary tree Node structure
 struct Node {
     int data; // the value of node
     struct Node *left, *right; // the left and right pointer to a node
 };
 // Allocate new memory to a node
 struct Node* newNode(int data)
 {
     struct Node* node = new Node; // create a new node
     node->data = data; // insert node value
     node->left = node->right = NULL; // the left and right pointers are currently NULL
     return (node); // return current node
 }
 // The function return true if contious tree exist else false
 bool treeContinuous(struct Node* ptr)
 {
     // if next node do not exist
     if (ptr == NULL) // return true
         return true;
     // when left and right are NULL it means current node is leaf node so return true
     if (ptr->left == NULL && ptr->right == NULL)
         return true;
     // the case where left subtree come empty
     if (ptr->left == NULL)
         return (abs(ptr->data - ptr->right->data) == 1) && treeContinuous(ptr->right);
     // the case where right subtree is empty
     if (ptr->right == NULL)
         return (abs(ptr->data - ptr->left->data) == 1) && treeContinuous(ptr->left);
     // the case where none of them is empty
     return abs(ptr->data - ptr->left->data) == 1 && abs(ptr->data - ptr->right->data) == 1 && treeContinuous(ptr->left) && treeContinuous(ptr->right); // call recursively for left and right
 }
 // Main function
 int main()
 {
     struct Node* root = newNode(3); // create root node
     root->left = newNode(2); // left child of root
     root->right = newNode(4); // right child of root
     root->left->left = newNode(1); // left child of parent left
     root->left->right = newNode(3); // right child of parent left
     root->right->right = newNode(5); // child of parent right
     treeContinuous(root) ? cout << "Yes" : cout << "No"; // call function to check contious
     return 0;
 } 

Output:

Yes

Approach 2:

We use a queue data structure in this approach and use BFS traversal. While traversing level by level we check if the difference between parent and child is one and the same is true for all the nodes until leaf node the tree is continuous.

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 // create a binary tree node structure
 struct node {
     int val; // node value
     node* left; // left pointer to node
     node* right; // right pointer to node
     node() // constructor
         : val(0) // initally node valye is zero
           ,
           left(nullptr) // left pointer is null
           ,
           right(nullptr) // right pointer is null
     {
     }
     node(int x) // parameterised constructor
         : val(x) // x value of a node
           ,
           left(nullptr) // left pointer is null
           ,
           right(nullptr) // right pointer is null
     {
     }
     node(int x, node* left, node* right) // constructor with left and right pointer
         : val(x) // x value of a node
           ,
           left(left) // left pointer point to passed left
           ,
           right(right) // right pointer pointing to passed right
     {
     }
 };
 // // The function return true if contious tree exist else false
 bool continuous(struct node* root)
 {
     // empty tree is not continuous return false
     if (root == NULL)
         return false;
     int flag = 1; // boolean flag
     queue<struct node*> Q; // queue data structure
     Q.push(root); // push root to queue
     node* temp; // create temp node
     // ITERATE UNITL QUEUE IS EMPTY
     while (!Q.empty()) {
         temp = Q.front(); // Take current node
         Q.pop(); // pop it from queue
         // if left child exist
         if (temp->left) {
             // check if difference between temp value and value of temp left is 1
             if (abs(temp->left->val - temp->val) == 1)
                 Q.push(temp->left); // push left to temp
             else {
                 flag = 0; // else flag become zero
                 break;
             }
         }
         // if right child exists
         if (temp->right) {
             // check if difference between temp value and value of temp right  is 1
             if (abs(temp->right->val - temp->val) == 1)
                 Q.push(temp->right); // push right  to temp
             else {
                 flag = 0; // else flag become zero
                 break;
             }
         }
     }
     if (flag) // check flag
         return true;
     else
         return false;
 }
 // Main function
 int main()
 {
     struct node* root = new node(3); // create root node with value 3
     root->left = new node(2); // left child of root
     root->right = new node(4); // right child of root
     root->left->left = new node(1); // left child of parent left
     root->left->right = new node(3); // right child of parent right
     root->right->right = new node(5); // right child of right node
     // check if continous tree
     if (continuous(root))
         cout << "Yes\n";
     else
         cout << "No\n";
     return 0;
 } 

Output:

Yes

Time complexity: O(n)


Related Topics

DAA: Euclid Algorithm

Euclid Algorithm The Euclid algorithm finds the GCD of two numbers in the efficient time complexity. To find the GCD of two numbers, we take the two numbers’ common factors and multiply...

8 minutes read.

DAA: Dynamic Programming

Dynamic Programming Introduction The technique of breaking a problem statement into subproblems and using the optimal result of subproblems as an optimal result of the problem statement is known as dynamic programming....

2 minutes read.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

Boyer Moore Algorithm

Boyer Moore Algorithm The Boyer Moore algorithm is a searching algorithm in which a string of length n and a pattern of length m is searched. It prints all the occurrences...

11 minutes read.

DAA: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its...

6 minutes read.

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.

DAA: Dijkstra’s Algorithm (Shortest Path)

Dijkstra’s Algorithm (Shortest Path) Dijkstra’s algorithm finds the shortest distance from a source to all the vertices in a graph. This algorithm is used in network protocols like IS-IS and OSPF(Open...

3 minutes read.

DAA: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

5 minutes read.

Recurrence relation in DAA

Recurrence relation in DAA The model that uses mathematical concepts to calculate the time complexity of an algorithm is known as the recurrence relational model. A recursive relation, T(n), is a recursive...

5 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

3 minutes read.

Segregate the given Linked List in DAA

Segregate Even and Odd Nodes in a Linked List A linked list is a linear data structure in which each node has two blocks. One contains the node’s value or data,...

3 minutes read.

DAA: Expression Trees

Expression Trees Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed. Example:...

4 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

Symmetric Trees in DAA

Symmetric Trees The trees that are mirror images of themselves are known as symmetric trees. Look at the following tree image below: The tree is symmetric as the left subtree is the mirror...

4 minutes read.

DAA: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.

DAA: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

5 minutes read.

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

DAA: Rabin Karp Algorithm

Rabin Karp Algorithm The Rabin Karp or Karp Rabin algorithm is used to matching a specific pattern in the string. It uses the technique of hashing to match a specific text. There also...

6 minutes read.

DAA: Floyd Cycle Detection

Floyd Cycle Detection Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers...

4 minutes read.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.