Check whether every node of binary tree has a value K on itself or its any immediate neighbours

Given a binary tree and a value K, the task is to check if every node of the binary tree has either value of the node as K or at least one of its adjacent connected nodes has value K.
Examples: 
 

Input:
                     1
                   /   \
                  0     0
                /   \     \
               1     0     1
              /     /  \    \
             2     1    0    5
                  /    /
                 3    0
                     /
                    0
K = 0
Output: False
Explanation: 
We can observe that some leaf nodes
are having value other than 0 and
are not connected with any
adjacent node whose value is 0. 

Input:
                    0
                   / \
                  2   1
                       \
                        0
K = 0  
Output: True
Explanation: 
Since, all nodes of the tree
are either having value 0 or
connected with adjacent node
having value 0.

 

Approach: 
 

  1. The idea is to simply perform preorder traversal and pass reference of parent node recursively.
  2. While traversing for each node check the following conditions: 
    • if value of the node is K or,
    • if its parent node value is K or,
    • if any of its child node value is K.
  3. If any node of the tree doesn’t satisfy any of the given three conditions then, return False, else return True.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach 
  
#include <iostream> 
#include <unordered_map> 
#include <vector> 
using namespace std; 
  
// Defining tree node 
struct node { 
    int value; 
    struct node *right, *left; 
}; 
  
// Utility function to create 
// a new node 
struct node* newnode(int key) 
    struct node* temp = new node; 
    temp->value = key; 
    temp->right = NULL; 
    temp->left = NULL; 
  
    return temp; 
  
// Function to check binary 
// tree whether its every node 
// has value K or, it is 
// connected with node having 
// value K 
bool connectedK(node* root, 
                node* parent, 
                int K, 
                bool flag) 
    // checking node value 
    if (root->value != K) { 
  
        // checking the left 
        // child value 
        if (root->left == NULL 
            || root->left->value != K) { 
  
            // checking the rigth 
            // child value 
            if (root->right == NULL 
                || root->right->value != K) { 
  
                // checking the parent value 
                if (parent == NULL 
                    || parent->value != K) { 
                    flag = false
                    return flag; 
                
            
        
    
  
    // Traversing to the left subtree 
    if (root->left != NULL) { 
        if (flag == true) { 
            flag 
                = connectedK(root->left, 
                            root, K, flag); 
        
    
  
    // Traversing to the right subtree 
    if (root->right != NULL) { 
        if (flag == true) { 
            flag 
                = connectedK(root->right, 
                            root, K, flag); 
        
    
    return flag; 
  
// Driver code 
int main() 
  
    // Input Binary tree 
    struct node* root = newnode(0); 
    root->right = newnode(1); 
    root->right->right = newnode(0); 
    root->left = newnode(0); 
  
    int K = 0; 
  
    // Function call to check 
    // binary tree 
    bool result 
        = connectedK(root, NULL, 
                    K, true); 
  
    if (result == false
        cout << "False\n"
    else
        cout << "True\n"
  
    return 0; 

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
  
# Defining tree node
class Node:
    def __init__(self,key):
          
        self.value = key
        self.left = None
        self.right = None
          
# Function to check binary 
# tree whether its every node 
# has value K or, it is 
# connected with node having 
# value K 
def connectedK(root, parent, K, flag):
      
    # Checking node value
    if root.value != K:
          
        # Checking the left 
        # child value 
        if (root.left == None or 
            root.left.value != K):
              
            # Checking the right 
            # child value 
            if (root.right == None or 
                root.right.value != K):
                  
                # Checking the parent value 
                if (parent == None or 
                    parent.value != K):
                    flag = False
                    return flag
                  
    # Traversing to the left subtree
    if root.left != None:
        if flag == True:
            flag = connectedK(root.left, 
                              root, K, flag)
      
    # Traversing to the right subtree
    if root.right != None:
        if flag == True:
            flag = connectedK(root.right, 
                              root, K, flag)
              
    return flag
  
# Driver code
root = Node(0)
root.right = Node(1)
root.right.right = Node(0)
root.left = Node(0)
  
K = 0
  
# Function call to check 
# binary tree 
result = connectedK(root, None, K, True)
  
if result == False:
    print("False")
else:
    print("True")
  
# This code is contributed by Stuti Pathak

chevron_right


Output:

True

Time complexity: O(N), N is the number of nodes of the tree.
Auxillary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : stutipathak31jan