Check if a Binary Tree is an Even-Odd Tree or not

Given a Binary Tree, the task is to check if the binary tree is an Even-Odd binary tree or not. 

A Binary Tree is called an Even-Odd Tree when all the nodes which are at even levels have even values (assuming root to be at level 0) and all the nodes which are at odd levels have odd values.

 Examples:

Input: 

             2
            / \
           3   9
          / \   \
         4   10  6

Output: YES 
Explanation: 
Only node on level 0 (even) is 2 (even). 
Nodes present in level 1 are 3 and 9 (both odd). 
Nodes present in level 2 are 4, 10 and 6 (all even). 
Therefore, the Binary tree is an odd-even binary tree.



Input:  

             4
            / \
           3   7
          / \   \
         4   10  5

Output: NO 
 

Approach: Follow the steps below to solve the problem: 

  1. The idea is to perform level-order traversal and check if the nodes present on even levels are even valued or not and nodes present on odd levels are odd valued or not.
  2. If any node at an odd level is found to have odd value or vice-versa, then print “NO“.
  3. Otherwise, after complete traversal of the tree, print “YES“.

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<bits/stdc++.h>
using namespace std;
 
struct Node
{
    int val;
    Node *left, *right;
};
 
struct Node* newNode(int data)
{
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
    temp->val = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}
 
// Function to check if the
// tree is even-odd tree
bool isEvenOddBinaryTree(Node *root)
{
    if (root == NULL)
        return true;
 
    // Stores nodes of each level
    queue<Node*> q;
    q.push(root);
 
    // Store the current level
    // of the binary tree
    int level = 0;
 
    // Traverse until the
    // queue is empty
    while (!q.empty())
    {
         
        // Stores the number of nodes
        // present in the current level
        int size = q.size();
 
        for(int i = 0; i < size; i++)
        {
            Node *node = q.front();
             
            // Check if the level
            // is even or odd
            if (level % 2 == 0)
            {
                if (node->val % 2 == 1)
                    return false;
            }
            else if (level % 2 == 1)
            {
                if (node->val % 2 == 0)
                    return true;
            }
 
            // Add the nodes of the next
            // level into the queue
            if (node->left != NULL)
            {
                q.push(node->left);
            }
            if (node->right != NULL)
            {
                q.push(node->right);
            }
        }
 
        // Increment the level count
        level++;
    }
    return true;
}
 
// Driver Code
int main()
{
     
    // Construct a Binary Tree
    Node *root = NULL;
    root = newNode(2);
    root->left = newNode(3);
    root->right = newNode(9);
    root->left->left = newNode(4);
    root->left->right = newNode(10);
    root->right->right = newNode(6);
 
    // Check if the binary tree
    // is even-odd tree or not
    if (isEvenOddBinaryTree(root))
        cout << "YES";
    else
        cout << "NO";
}
 
// This code is contributed by ipg2016107

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program for the above approach
import java.util.*;
 
class GfG {
 
    // Tree node
    static class Node {
        int val;
        Node left, right;
    }
 
    // Function to return new tree node
    static Node newNode(int data)
    {
        Node temp = new Node();
        temp.val = data;
        temp.left = null;
        temp.right = null;
        return temp;
    }
 
    // Function to check if the
    // tree is even-odd tree
    public static boolean
    isEvenOddBinaryTree(Node root)
    {
        if (root == null)
            return true;
 
        // Stores nodes of each level
        Queue<Node> q
            = new LinkedList<>();
        q.add(root);
 
        // Store the current level
        // of the binary tree
        int level = 0;
 
        // Traverse until the
        // queue is empty
        while (!q.isEmpty()) {
 
            // Stores the number of nodes
            // present in the current level
            int size = q.size();
 
            for (int i = 0; i < size; i++) {
                Node node = q.poll();
 
                // Check if the level
                // is even or odd
                if (level % 2 == 0) {
 
                    if (node.val % 2 == 1)
                        return false;
                }
                else if (level % 2 == 1) {
 
                    if (node.val % 2 == 0)
                        return false;
                }
 
                // Add the nodes of the next
                // level into the queue
                if (node.left != null) {
 
                    q.add(node.left);
                }
                if (node.right != null) {
 
                    q.add(node.right);
                }
            }
 
            // Increment the level count
            level++;
        }
 
        return true;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Construct a Binary Tree
        Node root = null;
        root = newNode(2);
        root.left = newNode(3);
        root.right = newNode(9);
        root.left.left = newNode(4);
        root.left.right = newNode(10);
        root.right.right = newNode(6);
 
        // Check if the binary tree
        // is even-odd tree or not
        if (isEvenOddBinaryTree(root)) {
 
            System.out.println("YES");
        }
        else {
 
            System.out.println("NO");
        }
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Tree node
class Node:
     
    def __init__(self, data):
         
        self.left = None
        self.right = None
        self.val = data
         
# Function to return new tree node
def newNode(data):
 
    temp = Node(data)
     
    return temp
 
# Function to check if the
# tree is even-odd tree
def isEvenOddBinaryTree(root):
     
    if (root == None):
        return True
  
    q = []
     
    # Stores nodes of each level
    q.append(root)
  
    # Store the current level
    # of the binary tree
    level = 0
  
    # Traverse until the
    # queue is empty
    while (len(q) != 0):
  
        # Stores the number of nodes
        # present in the current level
        size = len(q)
         
        for i in range(size):
            node = q[0]
            q.pop(0)
  
            # Check if the level
            # is even or odd
            if (level % 2 == 0):
  
                if (node.val % 2 == 1):
                    return False
                 
                elif (level % 2 == 1):
                    if (node.val % 2 == 0):
                        return False
                 
                # Add the nodes of the next
                # level into the queue
                if (node.left != None):
                    q.append(node.left)
                 
                if (node.right != None):
                    q.append(node.right)
                 
            # Increment the level count
            level += 1
         
        return True
     
# Driver code
if __name__=="__main__":
     
    # Construct a Binary Tree
    root = None
    root = newNode(2)
    root.left = newNode(3)
    root.right = newNode(9)
    root.left.left = newNode(4)
    root.left.right = newNode(10)
    root.right.right = newNode(6)
  
    # Check if the binary tree
    # is even-odd tree or not
    if (isEvenOddBinaryTree(root)):
        print("YES")
    else:
        print("NO")
        
# This code is contributed by rutvik_56

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program for the
// above approach
using System;
using System.Collections.Generic;
class GfG{
 
// Tree node
class Node
{
  public int val;
  public Node left, right;
}
 
// Function to return new
// tree node
static Node newNode(int data)
{
  Node temp = new Node();
  temp.val = data;
  temp.left = null;
  temp.right = null;
  return temp;
}
 
// Function to check if the
// tree is even-odd tree
static bool isEvenOddBinaryTree(Node root)
{
  if (root == null)
    return true;
 
  // Stores nodes of each level
  Queue<Node> q = new Queue<Node>();
  q.Enqueue(root);
 
  // Store the current level
  // of the binary tree
  int level = 0;
 
  // Traverse until the
  // queue is empty
  while (q.Count != 0)
  {
    // Stores the number of nodes
    // present in the current level
    int size = q.Count;
 
    for (int i = 0; i < size; i++)
    {
      Node node = q.Dequeue();
 
      // Check if the level
      // is even or odd
      if (level % 2 == 0)
      {
        if (node.val % 2 == 1)
          return false;
      }
      else if (level % 2 == 1)
      {
        if (node.val % 2 == 0)
          return false;
      }
 
      // Add the nodes of the next
      // level into the queue
      if (node.left != null)
      {
        q.Enqueue(node.left);
      }
      if (node.right != null)
      {
        q.Enqueue(node.right);
      }
    }
 
    // Increment the level count
    level++;
  }
 
  return true;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Construct a Binary Tree
  Node root = null;
  root = newNode(2);
  root.left = newNode(3);
  root.right = newNode(9);
  root.left.left = newNode(4);
  root.left.right = newNode(10);
  root.right.right = newNode(6);
 
  // Check if the binary tree
  // is even-odd tree or not
  if (isEvenOddBinaryTree(root))
  {
    Console.WriteLine("YES");
  }
  else
  {
    Console.WriteLine("NO");
  }
}
}
 
// This code is contributed by Princi Singh

chevron_right


Output: 

YES







 

Time Complexity: O(N)
Auxiliary Space: O(N)

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.