Open In App

Check whether a given binary tree is skewed binary tree or not?

Last Updated : 08 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Binary Tree check whether it is skewed binary tree or not. A skewed tree is a tree where each node has only one child node or none.

Examples: 

Input :         5
             /   
            4
              \
               3
             /
           2
Output : Yes

Input :       5
            /
           4
            \
             3
           /  \
          2    4
Output : No

The idea is to check if a node has two children. If node has two children return false, else recursively compute whether subtree with one child is skewed tree. If node is leaf node return true. 

Below is the implementation of above approach:

C++




// C++ program to Check whether a given
// binary tree is skewed binary tree or not?
 
#include <bits/stdc++.h>
using namespace std;
 
// A Tree node
struct Node {
    int key;
    struct Node *left, *right;
};
 
// Utility function to create a new node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
 
bool isSkewedBT(Node* root)
{
    // check if node is NULL or is a leaf node
    if (root == NULL || (root->left == NULL &&
                        root->right == NULL))
        return true;
 
    // check if node has two children if
    // yes, return false
    if (root->left && root->right)
        return false;
    if (root->left)
        return isSkewedBT(root->left);
    return isSkewedBT(root->right);
}
 
// Driver program
int main()
{
    /*   10
       /     \
     12       13
           /     \
         14       15   
        /   \     /  \
       21   22   23   24          
    Let us create Binary Tree shown in above example */
    Node* root = newNode(10);
    root->left = newNode(12);
    root->left->right = newNode(15);
    cout << isSkewedBT(root) << endl;
 
    root = newNode(5);
    root->right = newNode(4);
    root->right->left = newNode(3);
    root->right->left->right = newNode(2);
    cout << isSkewedBT(root) << endl;
 
    root = newNode(5);
    root->left = newNode(4);
    root->left->right = newNode(3);
    root->left->right->left = newNode(2);
    root->left->right->right = newNode(4);
    cout << isSkewedBT(root) << endl;
}


Java




// Java program to Check whether a given
// binary tree is skewed binary tree or not?
 
class Solution
{
// A Tree node
 static class Node {
    int key;
     Node left, right;
}
 
// Utility function to create a new node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.key = key;
    temp.left = temp.right = null;
    return (temp);
}
 
static boolean isSkewedBT(Node root)
{
    // check if node is null or is a leaf node
    if (root == null || (root.left == null &&
                        root.right == null))
        return true;
 
    // check if node has two children if
    // yes, return false
    if (root.left!=null && root.right!=null)
        return false;
    if (root.left!=null)
        return isSkewedBT(root.left);
    return isSkewedBT(root.right);
}
 
// Driver program
public static void main(String args[])
{
    /* 10
    /     \
    12     13
        /     \
        14     15    
        / \     / \
    21 22 23 24        
    Let us create Binary Tree shown in above example */
    Node root = newNode(10);
    root.left = newNode(12);
    root.left.right = newNode(15);
    System.out.println( isSkewedBT(root)?1:0 );
 
    root = newNode(5);
    root.right = newNode(4);
    root.right.left = newNode(3);
    root.right.left.right = newNode(2);
    System.out.println( isSkewedBT(root)?1:0 );
 
    root = newNode(5);
    root.left = newNode(4);
    root.left.right = newNode(3);
    root.left.right.left = newNode(2);
    root.left.right.right = newNode(4);
    System.out.println(  isSkewedBT(root)?1:0 );
}
}
//contributed by Arnab Kundu


Python3




# Python3 program to Check whether a given
# binary tree is skewed binary tree or not?
 
# Binary Tree Node
""" utility that allocates a newNode
with the given key """
class newNode:
 
    # Construct to create a newNode
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
def isSkewedBT(root):
 
    # check if node is None or is a leaf node
    if (root == None or (root.left == None and
                         root.right == None)):
        return 1
 
    # check if node has two children if
    # yes, return false
    if (root.left and root.right):
        return 0
    if (root.left) :
        return isSkewedBT(root.left)
    return isSkewedBT(root.right)
 
# Driver Code
if __name__ == '__main__':
 
    """ 10
    /     \
    12     13
        /     \
        14     15    
        / \     / \
    21 22 23 24        
    Let us create Binary Tree shown in above example """
    root = newNode(10)
    root.left = newNode(12)
    root.left.right = newNode(15)
    print(isSkewedBT(root))
 
    root = newNode(5)
    root.right = newNode(4)
    root.right.left = newNode(3)
    root.right.left.right = newNode(2)
    print(isSkewedBT(root))
 
    root = newNode(5)
    root.left = newNode(4)
    root.left.right = newNode(3)
    root.left.right.left = newNode(2)
    root.left.right.right = newNode(4)
    print(isSkewedBT(root))
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#




// C# program to Check whether a given
// binary tree is skewed binary tree or not?
using System;
 
public class GFG
{
     
// A Tree node
class Node
{
    public int key;
    public Node left, right;
}
 
// Utility function to create a new node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.key = key;
    temp.left = temp.right = null;
    return (temp);
}
 
static bool isSkewedBT(Node root)
{
    // check if node is null or is a leaf node
    if (root == null || (root.left == null &&
                        root.right == null))
        return true;
 
    // check if node has two children if
    // yes, return false
    if (root.left!=null && root.right!=null)
        return false;
    if (root.left!=null)
        return isSkewedBT(root.left);
    return isSkewedBT(root.right);
}
 
// Driver code
public static void Main()
{
    /* 10
    / \
    12 13
        / \
        14 15
        / \ / \
    21 22 23 24
    Let us create Binary Tree shown in above example */
    Node root = newNode(10);
    root.left = newNode(12);
    root.left.right = newNode(15);
    Console.WriteLine( isSkewedBT(root)?1:0 );
 
    root = newNode(5);
    root.right = newNode(4);
    root.right.left = newNode(3);
    root.right.left.right = newNode(2);
    Console.WriteLine( isSkewedBT(root)?1:0 );
 
    root = newNode(5);
    root.left = newNode(4);
    root.left.right = newNode(3);
    root.left.right.left = newNode(2);
    root.left.right.right = newNode(4);
    Console.WriteLine( isSkewedBT(root)?1:0 );
}
}
 
/* This code is contributed by Rajput-Ji*/


Javascript




<script>
    // Javascript program to Check whether a given
    // binary tree is skewed binary tree or not?
     
    // Binary tree node
    class Node
    {
        constructor(key) {
           this.left = null;
           this.right = null;
           this.data = key;
        }
    }
     
    // Utility function to create a new node
    function newNode(key)
    {
        let temp = new Node(key);
        return (temp);
    }
 
    function isSkewedBT(root)
    {
        // check if node is null or is a leaf node
        if (root == null || (root.left == null &&
                            root.right == null))
            return true;
 
        // check if node has two children if
        // yes, return false
        if (root.left!=null && root.right!=null)
            return false;
        if (root.left!=null)
            return isSkewedBT(root.left);
        return isSkewedBT(root.right);
    }
     
    /* 10
    /     \
    12     13
        /     \
        14     15    
        / \     / \
    21 22 23 24        
    Let us create Binary Tree shown in above example */
    let root = newNode(10);
    root.left = newNode(12);
    root.left.right = newNode(15);
    document.write(isSkewedBT(root)?1 + "</br>":0 + "</br>");
   
    root = newNode(5);
    root.right = newNode(4);
    root.right.left = newNode(3);
    root.right.left.right = newNode(2);
    document.write(isSkewedBT(root)?1 + "</br>":0 + "</br>");
   
    root = newNode(5);
    root.left = newNode(4);
    root.left.right = newNode(3);
    root.left.right.left = newNode(2);
    root.left.right.right = newNode(4);
    document.write(isSkewedBT(root)?1 + "</br>":0 + "</br>");
  
 // This code is contributed by decode2207.
</script>


Output

1
1
0

Complexity Analysis:

  • Time complexity: 
    • Best case : O(1) when root has two children. 
    • Worst case : O(h) when tree is skewed tree.
  • Auxiliary Space: O(h)
    • Here h is the height of the tree

Another approach:(iterative method)

We can also check if a tree is skewed or not by iterative method using above approach.

Implementation:

C++




// C++ program to Check whether a given
// binary tree is skewed binary tree or not using iterative
// method
 
#include <bits/stdc++.h>
using namespace std;
 
// A Tree node
struct Node {
    int key;
    struct Node *left, *right;
};
 
// Utility function to create a new node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
 
bool isSkewedBT(Node* root)
{
 
    while (root != NULL) {
        // check if the node is a leaf node
        if (root->left == NULL && root->right == NULL)
            return true;
        // check if node has two children if
        // yes, return false
        if (root->left != NULL && root->right != NULL)
            return false;
        // move towards left if it has a left child
        if (root->left != NULL)
            root = root->left;
        // or move towards right if it has a right child
        else
            root = root->right;
    }
    return true;
}
 
// Driver program
int main()
{
    /*   10
       /     \
     12       13
           /     \
         14       15
        /   \     /  \
       21   22   23   24
    Let us create Binary Tree shown in above example */
    Node* root = newNode(10);
    root->left = newNode(12);
    root->left->right = newNode(15);
    cout << isSkewedBT(root) << endl;
 
    root = newNode(5);
    root->right = newNode(4);
    root->right->left = newNode(3);
    root->right->left->right = newNode(2);
    cout << isSkewedBT(root) << endl;
 
    root = newNode(5);
    root->left = newNode(4);
    root->left->right = newNode(3);
    root->left->right->left = newNode(2);
    root->left->right->right = newNode(4);
    cout << isSkewedBT(root) << endl;
}
 
// This code is contributed by Abhijeet Kumar(abhijeet19403)


Java




// Java program to Check whether a given
// binary tree is skewed binary tree or not using iterative method
 
class Solution {
    // A Tree node
    static class Node {
        int key;
        Node left, right;
    }
 
    // Utility function to create a new node
    static Node newNode(int key)
    {
        Node temp = new Node();
        temp.key = key;
        temp.left = temp.right = null;
        return (temp);
    }
 
    static boolean isSkewedBT(Node root)
    {
        while (root != null) {
            // check if the node is a leaf node
            if (root.left == null && root.right == null)
                return true;
            // check if node has two children if
            // yes, return false
            if (root.left!=null && root.right!=null)
                return false;
              // move towards left if it has a left child
            if (root.left != null)
                root = root.left;
              // or move towards right if it has a right child
            else
                root = root.right;
        }
        return true;
    }
 
    // Driver program
    public static void main(String args[])
    {
        /* 10
        /     \
        12     13
            /     \
            14     15
            / \     / \
        21 22 23 24
        Let us create Binary Tree shown in above example */
        Node root = newNode(10);
        root.left = newNode(12);
        root.left.right = newNode(15);
        System.out.println(isSkewedBT(root) ? 1 : 0);
 
        root = newNode(5);
        root.right = newNode(4);
        root.right.left = newNode(3);
        root.right.left.right = newNode(2);
        System.out.println(isSkewedBT(root) ? 1 : 0);
 
        root = newNode(5);
        root.left = newNode(4);
        root.left.right = newNode(3);
        root.left.right.left = newNode(2);
        root.left.right.right = newNode(4);
        System.out.println(isSkewedBT(root) ? 1 : 0);
    }
}
// This code is contributed by Abhijeet Kumar(abhijeet19403)


Python3




# Python3 program to Check whether a given
# binary tree is skewed binary tree or not using iterative method
 
# Binary Tree Node
""" utility that allocates a newNode
with the given key """
 
 
class newNode:
 
    # Construct to create a newNode
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
 
def isSkewedBT(root):
 
    while (root != None):
            # check if the node is a leaf node
            if (root.left == None and root.right == None):
                return 1
            # check if node has two children if
            # yes, return false
            if (root.left != None and root.right != None):
                return 0
              # move towards left if it has a left child
            if (root.left != None):
                root = root.left
              # or move towards right if it has a right child
            else:
                root = root.right
 
    return 1
 
# Driver Code
if __name__ == '__main__':
 
    """ 10
    /     \
    12     13
        /     \
        14     15    
        / \     / \
    21 22 23 24        
    Let us create Binary Tree shown in above example """
    root = newNode(10)
    root.left = newNode(12)
    root.left.right = newNode(15)
    print(isSkewedBT(root))
 
    root = newNode(5)
    root.right = newNode(4)
    root.right.left = newNode(3)
    root.right.left.right = newNode(2)
    print(isSkewedBT(root))
 
    root = newNode(5)
    root.left = newNode(4)
    root.left.right = newNode(3)
    root.left.right.left = newNode(2)
    root.left.right.right = newNode(4)
    print(isSkewedBT(root))
 
# This code is contributed by
# Abhijeet Kumar(abhijeet19403)


C#




// C# program to Check whether a given
// binary tree is skewed binary tree or not using iterative method
using System;
 
public class GFG {
 
    // A Tree node
    class Node {
        public int key;
        public Node left, right;
    }
 
    // Utility function to create a new node
    static Node newNode(int key)
    {
        Node temp = new Node();
        temp.key = key;
        temp.left = temp.right = null;
        return (temp);
    }
 
    static bool isSkewedBT(Node root)
    {
        while (root != null) {
            // check if the node is a leaf node
            if (root.left == null && root.right == null)
                return true;
            // check if node has two children if
            // yes, return false
            if (root.left != null && root.right != null)
                return false;
            // move towards left if it has a left child
            if (root.left != null)
                root = root.left;
            // or move towards right if it has a right child
            else
                root = root.right;
        }
        return true;
    }
 
    // Driver code
    public static void Main()
    {
        /* 10
        / \
        12 13
            / \
            14 15
            / \ / \
        21 22 23 24
        Let us create Binary Tree shown in above example */
        Node root = newNode(10);
        root.left = newNode(12);
        root.left.right = newNode(15);
        Console.WriteLine(isSkewedBT(root) ? 1 : 0);
 
        root = newNode(5);
        root.right = newNode(4);
        root.right.left = newNode(3);
        root.right.left.right = newNode(2);
        Console.WriteLine(isSkewedBT(root) ? 1 : 0);
 
        root = newNode(5);
        root.left = newNode(4);
        root.left.right = newNode(3);
        root.left.right.left = newNode(2);
        root.left.right.right = newNode(4);
        Console.WriteLine(isSkewedBT(root) ? 1 : 0);
    }
}
 
/* This code is contributed by Abhijeet
 * Kumar(abhijeet19403)*/


Javascript




<script>
    // Javascript program to Check whether a given
    // binary tree is skewed binary tree or not?
     
    // Binary tree node
    class Node
    {
        constructor(key) {
           this.left = null;
           this.right = null;
           this.data = key;
        }
    }
     
    // Utility function to create a new node
    function newNode(key)
    {
        let temp = new Node(key);
        return (temp);
    }
 
    function isSkewedBT(root)
    {
          while (root != null) {
            // check if the node is a leaf node
            if (root.left == null && root.right == null)
                return true;
            // check if node has two children if
            // yes, return false
            if (root.left != null && root.right != null)
                return false;
            // move towards left if it has a left child
            if (root.left != null)
                root = root.left;
            // or move towards right if it has a right child
            else
                root = root.right;
        }
        return true;
    }
     
    /* 10
    /     \
    12     13
        /     \
        14     15    
        / \     / \
    21 22 23 24        
    Let us create Binary Tree shown in above example */
    let root = newNode(10);
    root.left = newNode(12);
    root.left.right = newNode(15);
    document.write(isSkewedBT(root)?1 + "</br>":0 + "</br>");
   
    root = newNode(5);
    root.right = newNode(4);
    root.right.left = newNode(3);
    root.right.left.right = newNode(2);
    document.write(isSkewedBT(root)?1 + "</br>":0 + "</br>");
   
    root = newNode(5);
    root.left = newNode(4);
    root.left.right = newNode(3);
    root.left.right.left = newNode(2);
    root.left.right.right = newNode(4);
    document.write(isSkewedBT(root)?1 + "</br>":0 + "</br>");
  
 // This code is contributed by Abhijeet Kumar(abhijeet19403)
</script>


Output

1
1
0

Complexity Analysis:

  • Time Complexity: O(n)
    • As in the worst case we have to visit every node.
  • Auxiliary Space: O(1)
    • As constant extra space is used.

This approach was contributed by Ahijeet Kumar.



Similar Reads

Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
Given a Binary Search Tree and a binary integer K, the task is to convert Binary search tree into a Skewed Tree in increasing order if K = 0 or in decreasing order if K = 1. Examples: Input: K = 0, 5 / \ 3 6 Output: 3 \ 5 \ 6 Input: K = 1, 2 / \ 1 3 Output: 3 \ 2 \ 1 Approach: The key observation in the problem is that the first node of the skewed
10 min read
Skewed Binary Tree
A skewed binary tree is a type of binary tree in which all the nodes have only either one child or no child. Types of Skewed Binary trees There are 2 special types of skewed tree: 1. Left Skewed Binary Tree: These are those skewed binary trees in which all the nodes are having a left child or no child at all. It is a left side dominated tree. All t
5 min read
Ways to color a skewed tree such that parent and child have different colors
Given a skewed tree (Every node has at most one child) with N nodes and K colors. You have to assign a color from 1 to K to each node such that parent and child has different colors. Find the maximum number of ways of coloring the nodes. Examples: Input : N = 2, K = 2. Output : Let A1 and A2 be the two nodes. Let A1 is parent of A2. Colors are Red
6 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Check whether a binary tree is a full binary tree or not
A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here. For Example : Recommended PracticeFull binary treeTry It! To check whether a binary tree is a full binary tre
14 min read
Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
A complete binary tree is a binary tree whose all levels except the last level are completely filled and all the leaves in the last level are all to the left side. More information about complete binary trees can be found here. Example:Below tree is a Complete Binary Tree (All nodes till the second last nodes are filled and all leaves are to the le
10 min read
Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
Given a Binary Tree, write a function to check whether the given Binary Tree is Complete Binary Tree or not.A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. See the following examples. The following trees are examples of Complete Binary Trees 1 /
15+ min read
Check whether a given binary tree is perfect or not
Given a Binary Tree, write a function to check whether the given Binary Tree is a perfect Binary Tree or not.A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are at same level. Examples: The following tree is a perfect binary tree 10 / \ 20 30 / \ / \ 40 50 60 70 18 / \ 15 30 The following tree is no
15+ min read
Check whether the binary equivalent of a number ends with given string or not
Given a positive integer N, the task is to check whether the binary equivalent of that integer ends with the given string str or not. Print "Yes" if it ends in "str". Otherwise, Print "No".Examples: Input: N = 23, str = "111"Output: YesExplanation:Binary of 23 = 10111, which ends with "111" Input: N = 5, str = "111"Output: No Approach: The idea is
5 min read
Javascript Program for Check whether all the rotations of a given number is greater than or equal to the given number or not
Given an integer x, the task is to find if every k-cycle shift on the element produces a number greater than or equal to the same element. A k-cyclic shift of an integer x is a function that removes the last k digits of x and inserts them in its beginning. For example, the k-cyclic shifts of 123 are 312 for k=1 and 231 for k=2. Print Yes if the giv
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg