Check if a Binary Tree contains node values in strictly increasing and decreasing order at even and odd levels

Given a Binary Tree, the task is to check if it consists of node values arranged in strictly increasing order at even levels and strictly decreasing at odd levels (Assuming the root node to be at level 0).

Examples:

Input: 

             2
            / \
           6   3
          / \   \
         4   7   11
        / \   \
       10  5   1

Output: YES 
Explanation: 
At level 1 (odd), Node values 6 and 3 are in strictly decreasing order. 
At level 2 (even), Node values 4, 7, and 11 are in strictly increasing order. 
At level 3 (odd), Node values 10, 5, and 1) are in strictly decreasing order. 
Therefore, the tree satisfies the given conditions.

Input: 



             5
            / \
           6   3
          / \   \
         4   9   2

Output: NO 

Approach: The idea is to perform Level Order Traversal on the given Binary Tree and for each level, check if it satisfies the given conditions or not. Follow the steps below to solve the problem:

  • Create an empty Queue to store nodes of each level one by one during the Level Order Traversal of the tree.
  • Push the root node into the Queue.
  • Iterate until the queue is empty and perform the following: 
    • Keep popping nodes of the current level from the queue and insert it into an Arraylist. Push all of its children nodes into the Queue.
    • If the level is even, check if elements present in the Arraylist is in increasing order or not. If found to be true, proceed to the next level. Otherwise, print No.
    • Similarly, check for the odd levels.
    • After complete traversal of the tree, if all levels are found to be satisfying the conditions, 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 given binary
// tree satisfies the required conditons
bool checkEvenOddLevel(Node *root)
{
    if (root == NULL)
        return true;
 
    // Queue to store nodes
    // of each level
    queue<Node*> q;
    q.push(root);
 
    // Stores the current
    // level of the binary tree
    int level = 0;
 
    // Traverse until the
    // queue is empty
    while (q.empty())
    {
        vector<int> vec;
 
        // 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();
            vec.push_back(node->val);
 
            // Insert left and right child
            // of node into the queue
            if (node->left != NULL)
                q.push(node->left);
 
            if (node->right != NULL)
                q.push(node->right);
        }
 
        // If the level is even
        if (level % 2 == 0)
        {
             
            // If the nodes in this
            // level are in strictly
            // increasing order or not
            for(int i = 0; i < vec.size() - 1; i++)
            {
                if (vec[i + 1] > vec[i])
                    continue;
                     
                return false;
            }
        }
 
        // If the level is odd
        else if (level % 2 == 1)
        {
             
            // If the nodes in this
            // level are in strictly
            // decreasing order or not
            for(int i = 0; i < vec.size() - 1; i++)
            {
                if (vec[i + 1] < vec[i])
                    continue;
                     
                return false;
            }
        }
 
        // Increment the level count
        level++;
    }
    return true;
}
 
// Driver Code
int main()
{
     
    // Construct a Binary Tree
    Node *root = NULL;
    root = newNode(2);
    root->left = newNode(6);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(7);
    root->right->right = newNode(11);
    root->left->left->left = newNode(10);
    root->left->left->right = newNode(5);
    root->left->right->right = newNode(1);
 
    // Function Call
    if (checkEvenOddLevel(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 {
 
    // Structure of Tree node
    static class Node {
        int val;
        Node left, right;
    }
 
    // Function to create 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 given binary
    // tree satisfies the required conditons
    public static boolean
    checkEvenOddLevel(Node root)
    {
        if (root == null)
            return true;
 
        // Queue to store nodes
        // of each level
        Queue<Node> q
            = new LinkedList<>();
        q.add(root);
 
        // Stores the current
        // level of the binary tree
        int level = 0;
 
        // Traverse until the
        // queue is empty
        while (!q.isEmpty()) {
 
            ArrayList<Integer> list
                = new ArrayList<>();
 
            // 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();
                list.add(node.val);
 
                // Insert left and right child
                // of node into the queue
                if (node.left != null)
                    q.add(node.left);
 
                if (node.right != null)
                    q.add(node.right);
            }
 
            // If the level is even
            if (level % 2 == 0) {
 
                // If the nodes in this
                // level are in strictly
                // increasing order or not
                for (int i = 0; i < list.size() - 1;
                     i++) {
 
                    if (list.get(i + 1) > list.get(i))
                        continue;
                    return false;
                }
            }
 
            // If the level is odd
            else if (level % 2 == 1) {
 
                // If the nodes in this
                // level are in strictly
                // decreasing order or not
                for (int i = 0; i < list.size() - 1;
                     i++) {
 
                    if (list.get(i + 1) < list.get(i))
                        continue;
                    return false;
                }
            }
 
            // 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(6);
        root.right = newNode(3);
        root.left.left = newNode(4);
        root.left.right = newNode(7);
        root.right.right = newNode(11);
        root.left.left.left = newNode(10);
        root.left.left.right = newNode(5);
        root.left.right.right = newNode(1);
 
        // Function Call
        if (checkEvenOddLevel(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 checkEvenOddLevel(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):
        l = []
         
        # Stores the number of nodes
        # present in the current level
        size = len(q)
         
        for i in range(size):
            node = q[0]
            q.pop(0)
  
            # Insert left and right child
            # of node into the queue
            if (node.left != None):
                q.append(node.left);
  
            if (node.right != None):
                q.append(node.right);
             
            # If the level is even
            if (level % 2 == 0):
  
                # If the nodes in this
                # level are in strictly
                # increasing order or not
                for i in range(len(l) - 1):
                    if (l[i + 1] > l[i]):
                        continue
                         
                    return False
                 
            # If the level is odd
            elif (level % 2 == 1):
  
                # If the nodes in this
                # level are in strictly
                # decreasing order or not
                for i in range(len(l) - 1):
                    if (l[i + 1] < l[i]):
                        continue
                         
                    return False
         
            # 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(6)
    root.right = newNode(3)
    root.left.left = newNode(4)
    root.left.right = newNode(7)
    root.right.right = newNode(11)
    root.left.left.left = newNode(10)
    root.left.left.right = newNode(5)
    root.left.right.right = newNode(1)
  
    # Check if the binary tree
    # is even-odd tree or not
    if (checkEvenOddLevel(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{
 
// Structure of Tree node
public class Node
{
  public int val;
  public Node left, right;
}
 
// Function to create
// 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 given binary
// tree satisfies the required conditons
public static bool checkEvenOddLevel(Node root)
{
  if (root == null)
    return true;
 
  // Queue to store nodes
  // of each level
  Queue<Node> q =
              new Queue<Node>();
  q.Enqueue(root);
 
  // Stores the current
  // level of the binary tree
  int level = 0;
 
  // Traverse until the
  // queue is empty
  while (q.Count != 0)
  {
    List<int> list =
              new List<int>();
 
    // 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();
      list.Add(node.val);
 
      // Insert left and right child
      // of node into the queue
      if (node.left != null)
        q.Enqueue(node.left);
 
      if (node.right != null)
        q.Enqueue(node.right);
    }
 
    // If the level is even
    if (level % 2 == 0)
    {
      // If the nodes in this
      // level are in strictly
      // increasing order or not
      for (int i = 0;
               i < list.Count - 1; i++)
      {
        if (list[i + 1] > list[i])
          continue;
        return false;
      }
    }
 
    // If the level is odd
    else if (level % 2 == 1)
    {
      // If the nodes in this
      // level are in strictly
      // decreasing order or not
      for (int i = 0;
               i < list.Count - 1; i++)
      {
        if (list[i + 1] < list[i])
          continue;
        return false;
      }
    }
 
    // 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(6);
  root.right = newNode(3);
  root.left.left = newNode(4);
  root.left.right = newNode(7);
  root.right.right = newNode(11);
  root.left.left.left = newNode(10);
  root.left.left.right = newNode(5);
  root.left.right.right = newNode(1);
 
  // Function Call
  if (checkEvenOddLevel(root))
  {
    Console.WriteLine("YES");
  }
  else
  {
    Console.WriteLine("NO");
  }
}
}
 
// This code is contributed by Rajput-Ji

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.