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++
#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;
}
bool checkEvenOddLevel(Node *root)
{
if (root == NULL)
return true ;
queue<Node*> q;
q.push(root);
int level = 0;
while (q.empty())
{
vector< int > vec;
int size = q.size();
for ( int i = 0; i < size; i++)
{
Node *node = q.front();
vec.push_back(node->val);
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
}
if (level % 2 == 0)
{
for ( int i = 0; i < vec.size() - 1; i++)
{
if (vec[i + 1] > vec[i])
continue ;
return false ;
}
}
else if (level % 2 == 1)
{
for ( int i = 0; i < vec.size() - 1; i++)
{
if (vec[i + 1] < vec[i])
continue ;
return false ;
}
}
level++;
}
return true ;
}
int main()
{
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);
if (checkEvenOddLevel(root))
cout << "YES" ;
else
cout << "NO" ;
}
|
Java
import java.util.*;
class GFG {
static class Node {
int val;
Node left, right;
}
static Node newNode( int data)
{
Node temp = new Node();
temp.val = data;
temp.left = null ;
temp.right = null ;
return temp;
}
public static boolean
checkEvenOddLevel(Node root)
{
if (root == null )
return true ;
Queue<Node> q
= new LinkedList<>();
q.add(root);
int level = 0 ;
while (!q.isEmpty()) {
ArrayList<Integer> list
= new ArrayList<>();
int size = q.size();
for ( int i = 0 ; i < size; i++) {
Node node = q.poll();
list.add(node.val);
if (node.left != null )
q.add(node.left);
if (node.right != null )
q.add(node.right);
}
if (level % 2 == 0 ) {
for ( int i = 0 ; i < list.size() - 1 ;
i++) {
if (list.get(i + 1 ) > list.get(i))
continue ;
return false ;
}
}
else if (level % 2 == 1 ) {
for ( int i = 0 ; i < list.size() - 1 ;
i++) {
if (list.get(i + 1 ) < list.get(i))
continue ;
return false ;
}
}
level++;
}
return true ;
}
public static void main(String[] args)
{
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 );
if (checkEvenOddLevel(root)) {
System.out.println( "YES" );
}
else {
System.out.println( "NO" );
}
}
}
|
Python3
class Node:
def __init__( self , data):
self .left = None
self .right = None
self .val = data
def newNode(data):
temp = Node(data)
return temp
def checkEvenOddLevel(root):
if (root = = None ):
return True
q = []
q.append(root)
level = 0
while ( len (q) ! = 0 ):
l = []
size = len (q)
for i in range (size):
node = q[ 0 ]
q.pop( 0 )
if (node.left ! = None ):
q.append(node.left);
if (node.right ! = None ):
q.append(node.right);
if (level % 2 = = 0 ):
for i in range ( len (l) - 1 ):
if (l[i + 1 ] > l[i]):
continue
return False
elif (level % 2 = = 1 ):
for i in range ( len (l) - 1 ):
if (l[i + 1 ] < l[i]):
continue
return False
level + = 1
return True
if __name__ = = "__main__" :
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 )
if (checkEvenOddLevel(root)):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
using System.Collections.Generic;
class GFG{
public class Node
{
public int val;
public Node left, right;
}
static Node newNode( int data)
{
Node temp = new Node();
temp.val = data;
temp.left = null ;
temp.right = null ;
return temp;
}
public static bool checkEvenOddLevel(Node root)
{
if (root == null )
return true ;
Queue<Node> q =
new Queue<Node>();
q.Enqueue(root);
int level = 0;
while (q.Count != 0)
{
List< int > list =
new List< int >();
int size = q.Count;
for ( int i = 0; i < size; i++)
{
Node node = q.Dequeue();
list.Add(node.val);
if (node.left != null )
q.Enqueue(node.left);
if (node.right != null )
q.Enqueue(node.right);
}
if (level % 2 == 0)
{
for ( int i = 0;
i < list.Count - 1; i++)
{
if (list[i + 1] > list[i])
continue ;
return false ;
}
}
else if (level % 2 == 1)
{
for ( int i = 0;
i < list.Count - 1; i++)
{
if (list[i + 1] < list[i])
continue ;
return false ;
}
}
level++;
}
return true ;
}
public static void Main(String[] args)
{
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);
if (checkEvenOddLevel(root))
{
Console.WriteLine( "YES" );
}
else
{
Console.WriteLine( "NO" );
}
}
}
|
Javascript
<script>
class Node
{
constructor(data)
{
this .left = null ;
this .right = null ;
this .val = data;
}
}
function newNode(data)
{
let temp = new Node(data);
return temp;
}
function checkEvenOddLevel(root)
{
if (root == null )
return true ;
let q = [];
q.push(root);
let level = 0;
while (q.length > 0)
{
let list = [];
let size = q.length;
for (let i = 0; i < size; i++)
{
let node = q[0];
q.shift();
list.push(node.val);
if (node.left != null )
q.push(node.left);
if (node.right != null )
q.push(node.right);
}
if (level % 2 == 0)
{
for (let i = 0; i < list.length - 1; i++)
{
if (list[i + 1] > list[i])
continue ;
return false ;
}
}
else if (level % 2 == 1)
{
for (let i = 0; i < list.length - 1; i++)
{
if (list[i + 1] < list[i])
continue ;
return false ;
}
}
level++;
}
return true ;
}
let 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);
if (checkEvenOddLevel(root))
{
document.write( "YES" );
}
else
{
document.write( "NO" );
}
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
07 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...