Open In App

Check if each internal node of a BST has exactly one child

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given Preorder traversal of a BST, check if each non-leaf node has only one child. Assume that the BST contains unique entries.

Examples :

Input: pre[] = {20, 10, 11, 13, 12}
Output: Yes
The given array represents following BST. In the following BST, every internal
node has exactly 1 child. Therefore, the output is true.
20
/
10
\
11
\
13
/
12

In Preorder traversal, descendants (or Preorder successors) of every node appear after the node. In the above example, 20 is the first node in preorder and all descendants of 20 appear after it. All descendants of 20 are smaller than it. For 10, all descendants are greater than it. In general, we can say, if all internal nodes have only one child in a BST, then all the descendants of every node are either smaller or larger than the node. The reason is simple, since the tree is BST and every node has only one child, all descendants of a node will either be on left side or right side, means all descendants will either be smaller or greater.

Approach 1 (Naive):
This approach simply follows the above idea that all values on right side are either smaller or larger. Use two loops, the outer loop picks an element one by one, starting from the leftmost element. The inner loop checks if all elements on the right side of the picked element are either smaller or greater. The time complexity of this method will be O(n^2).

Approach 2:
Since all the descendants of a node must either be larger or smaller than the node. We can do the following for every node in a loop. 

  1. Find the next preorder successor (or descendant) of the node. 
  2. Find the last preorder successor (last element in pre[]) of the node. 
  3. If both successors are less than the current node, or both successors are greater than the current node, then continue. Else, return false.

Below is the implementation of the above approach:

C++




#include<bits/stdc++.h>
using namespace std;
 
bool hasOnlyOneChild(int pre[], int size)
{
    int nextDiff, lastDiff;
 
    for (int i=0; i<size-1; i++)
    {
        nextDiff = pre[i] - pre[i+1];
        lastDiff = pre[i] - pre[size-1];
        if (nextDiff*lastDiff < 0)
            return false;;
    }
    return true;
}
 
// driver program to test above function
int main()
{
    int pre[] = {8, 3, 5, 7, 6};
    int size = sizeof(pre)/sizeof(pre[0]);
    if (hasOnlyOneChild(pre, size) == true )
        cout<<"Yes";
    else
        cout<<"No";
    return 0;
}
 
// This code is contributed by rrrtnx.


C




#include <stdio.h>
 
bool hasOnlyOneChild(int pre[], int size)
{
    int nextDiff, lastDiff;
 
    for (int i=0; i<size-1; i++)
    {
        nextDiff = pre[i] - pre[i+1];
        lastDiff = pre[i] - pre[size-1];
        if (nextDiff*lastDiff < 0)
            return false;;
    }
    return true;
}
 
// driver program to test above function
int main()
{
    int pre[] = {8, 3, 5, 7, 6};
    int size = sizeof(pre)/sizeof(pre[0]);
    if (hasOnlyOneChild(pre, size) == true )
        printf("Yes");
    else
        printf("No");
    return 0;
}


Java




// Check if each internal node of BST has only one child
 
class BinaryTree {
 
    boolean hasOnlyOneChild(int pre[], int size) {
        int nextDiff, lastDiff;
 
        for (int i = 0; i < size - 1; i++) {
            nextDiff = pre[i] - pre[i + 1];
            lastDiff = pre[i] - pre[size - 1];
            if (nextDiff * lastDiff < 0) {
                return false;
            };
        }
        return true;
    }
 
    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        int pre[] = new int[]{8, 3, 5, 7, 6};
        int size = pre.length;
        if (tree.hasOnlyOneChild(pre, size) == true) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
 
// This code has been contributed by Mayank Jaiswal


Python3




# Check if each internal
# node of BST has only one child
 
def hasOnlyOneChild (pre, size):
    nextDiff=0; lastDiff=0
  
    for i in range(size-1):
        nextDiff = pre[i] - pre[i+1]
        lastDiff = pre[i] - pre[size-1]
        if nextDiff*lastDiff < 0:
            return False
    return True
  
# driver program to
# test above function
if __name__ == "__main__":
 
    pre = [8, 3, 5, 7, 6]
    size= len(pre)
 
    if (hasOnlyOneChild(pre,size) == True):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by
# Harshit Saini


C#




// Check if each internal node of BST has only one child
using System;
public class BinaryTree
{
 
  bool hasOnlyOneChild(int[] pre, int size)
  {
    int nextDiff, lastDiff;
    for (int i = 0; i < size - 1; i++)
    {
      nextDiff = pre[i] - pre[i + 1];
      lastDiff = pre[i] - pre[size - 1];
      if (nextDiff * lastDiff < 0)
      {
        return false;
      };
    }
    return true;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    BinaryTree tree = new BinaryTree();
    int []pre = new int[]{8, 3, 5, 7, 6};
    int size = pre.Length;
    if (tree.hasOnlyOneChild(pre, size) == true)
    {
      Console.WriteLine("Yes");
    }
    else
    {
      Console.WriteLine("No");
    }
  }
}
 
// This code is contributed by aashish1995


Javascript




<script>
  
// Check if each internal node of BST has only one child
function hasOnlyOneChild(pre, size)
{
  var nextDiff, lastDiff;
  for (var i = 0; i < size - 1; i++)
  {
    nextDiff = pre[i] - pre[i + 1];
    lastDiff = pre[i] - pre[size - 1];
    if (nextDiff * lastDiff < 0)
    {
      return false;
    };
  }
  return true;
}
 
// Driver code
var pre = [8, 3, 5, 7, 6];
var size = pre.length;
if (hasOnlyOneChild(pre, size) == true)
{
  document.write("Yes");
}
else
{
  document.write("No");
}
 
// This code is contributed by itsok.
</script>


Output

Yes





Time Complexity: O(n), where n is the length of the given pre[] array.
Auxiliary Space: O(1)

Approach 3 :

  1. Scan the last two nodes of preorder & mark them as min & max. 
  2. Scan every node down the preorder array. Each node must be either smaller than the min node or larger than the max node. Update min & max accordingly. 

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
int hasOnlyOneChild(int pre[], int size)
{
     
    // Initialize min and max using last two elements
    int min, max;
    if (pre[size - 1] > pre[size - 2])
    {
        max = pre[size - 1];
        min = pre[size - 2];
    }
    else
    {
        max = pre[size - 2];
        min = pre[size - 1];
    }
 
    // Every element must be either smaller
    // than min or greater than max
    for(int i = size - 3; i >= 0; i--)
    {
        if (pre[i] < min)
            min = pre[i];
        else if (pre[i] > max)
            max = pre[i];
        else
            return false;
    }
    return true;
}
 
// Driver code
int main()
{
    int pre[] = { 8, 3, 5, 7, 6 };
    int size = sizeof(pre) / sizeof(pre[0]);
     
    if (hasOnlyOneChild(pre,size))
        cout <<"Yes";
    else
        cout <<"No";
         
    return 0;
}
 
// This code is contributed by shivanisinghss2110


C




#include <stdio.h>
 
int hasOnlyOneChild(int pre[], int size)
{
    // Initialize min and max using last two elements
    int min, max;
    if (pre[size-1] > pre[size-2])
    {
        max = pre[size-1];
        min = pre[size-2];
    }
    else
    {
        max = pre[size-2];
        min = pre[size-1];
    }
 
 
    // Every element must be either smaller than min or
    // greater than max
    for (int i=size-3; i>=0; i--)
    {
        if (pre[i] < min)
            min = pre[i];
        else if (pre[i] > max)
            max = pre[i];
        else
            return false;
    }
    return true;
}
 
// Driver program to test above function
int main()
{
    int pre[] = {8, 3, 5, 7, 6};
    int size = sizeof(pre)/sizeof(pre[0]);
    if (hasOnlyOneChild(pre,size))
        printf("Yes");
    else
        printf("No");
    return 0;
}


Java




// Check if each internal node of BST has only one child
 
class BinaryTree {
 
    boolean hasOnlyOneChild(int pre[], int size) {
        // Initialize min and max using last two elements
        int min, max;
        if (pre[size - 1] > pre[size - 2]) {
            max = pre[size - 1];
            min = pre[size - 2];
        } else {
            max = pre[size - 2];
            min = pre[size - 1];
        }
 
        // Every element must be either smaller than min or
        // greater than max
        for (int i = size - 3; i >= 0; i--) {
            if (pre[i] < min) {
                min = pre[i];
            } else if (pre[i] > max) {
                max = pre[i];
            } else {
                return false;
            }
        }
        return true;
    }
 
    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        int pre[] = new int[]{8, 3, 5, 7, 6};
        int size = pre.length;
        if (tree.hasOnlyOneChild(pre, size) == true) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
 
// This code has been contributed by Mayank Jaiswal


Python3




# Check if each internal
# node of BST has only one child
# approach 2
 
def hasOnlyOneChild(pre,size):
 
    # Initialize min and max
    # using last two elements
    min=0; max=0
 
    if pre[size-1] > pre[size-2] :
        max = pre[size-1]
        min = pre[size-2]
    else :
        max = pre[size-2]
        min = pre[size-1]
  
    # Every element must be
    # either smaller than min or
    # greater than max
    for i in range(size-3, 0, -1):
        if pre[i] < min:
            min = pre[i]
        elif pre[i] > max:
            max = pre[i]
        else:
            return False
    return True
  
# Driver program to
# test above function
if __name__ == "__main__":
 
    pre = [8, 3, 5, 7, 6]
 
    size = len(pre)
    if (hasOnlyOneChild(pre, size)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by
# Harshit Saini


C#




// Check if each internal node of BST has only one child
using System;
public class BinaryTree
{
 
  bool hasOnlyOneChild(int []pre, int size)
  {
 
    // Initialize min and max using last two elements
    int min, max;
    if (pre[size - 1] > pre[size - 2]) {
      max = pre[size - 1];
      min = pre[size - 2];
    } else {
      max = pre[size - 2];
      min = pre[size - 1];
    }
 
    // Every element must be either smaller than min or
    // greater than max
    for (int i = size - 3; i >= 0; i--) {
      if (pre[i] < min) {
        min = pre[i];
      } else if (pre[i] > max) {
        max = pre[i];
      } else {
        return false;
      }
    }
    return true;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    BinaryTree tree = new BinaryTree();
    int []pre = new int[]{8, 3, 5, 7, 6};
    int size = pre.Length;
    if (tree.hasOnlyOneChild(pre, size) == true)
    {
      Console.WriteLine("Yes");
    }
    else
    {
      Console.WriteLine("No");
    }
  }
}
 
// This code is contributed by aashish1995


Javascript




<script>
 
      // Check if each internal node of BST
      // has only one child
      class BinaryTree {
        hasOnlyOneChild(pre, size) {
          // Initialize min and max using
          // last two elements
          var min, max;
          if (pre[size - 1] > pre[size - 2]) {
            max = pre[size - 1];
            min = pre[size - 2];
          } else {
            max = pre[size - 2];
            min = pre[size - 1];
          }
 
          // Every element must be either
          // smaller than min or
          // greater than max
          for (var i = size - 3; i >= 0; i--) {
            if (pre[i] < min) {
              min = pre[i];
            } else if (pre[i] > max) {
              max = pre[i];
            } else {
              return false;
            }
          }
          return true;
        }
      }
      // Driver code
      var tree = new BinaryTree();
      var pre = [8, 3, 5, 7, 6];
      var size = pre.length;
      if (tree.hasOnlyOneChild(pre, size) == true) {
        document.write("Yes");
      } else {
        document.write("No");
      }
       
</script>


Output

Yes





Time Complexity: O(n), where n is the length of the given pre[] array.
Auxiliary Space: O(1)

Approach 4:

  1. Create a function hasOnlyOneChild that takes an integer array pre and its size size as input.
  2. Initialize min and max as the last two elements of the pre array. This is because the last element in the preorder traversal must be either the rightmost element in the tree or its ancestor.
  3. For each element in the pre array starting from size – 3 to 0, do the following:                                                                                                                   a) If the element is less than the min value, update min to the element.
    b) If the element is greater than the max value, update max to the element.
    c) If the element is between min and max, return false, since the node has more than one child.
    d) If the loop completes without returning false, then all nodes have only one child, so return true.
  4. In the main function, initialize an integer array pre and its size size.
  5. Call the hasOnlyOneChild function with pre and size as arguments and store the returned value in a boolean variable.
  6. If the boolean value is true, print “Yes”. Otherwise, print “No”.
  7. End the program.

C++




#include<bits/stdc++.h>
using namespace std;
 
bool hasOnlyOneChild(int pre[], int size) {
    int max_val = INT_MAX, min_val = INT_MIN; // initialize max and min to extreme values
    for (int i = 1; i < size; i++) {
        if (pre[i] < min_val || pre[i] > max_val) {
            return false;
        }
        if (pre[i] < pre[i-1]) {
            max_val = pre[i-1];
        } else {
            min_val = pre[i-1];
        }
    }
    return true;
}
 
 
// driver program to test above function
int main()
{
    int pre[] = {8, 3, 5, 7, 6};
    int size = sizeof(pre)/sizeof(pre[0]);
    if (hasOnlyOneChild(pre, size) == true )
        cout<<"Yes";
    else
        cout<<"No";
    return 0;
}


Java




// Java code for above approach
import java.io.*;
 
class GFG {
     
    static boolean hasOnlyOneChild(int pre[], int size) {
    int max_val = Integer.MAX_VALUE, min_val = Integer.MIN_VALUE; // initialize max and min to extreme values
    for (int i = 1; i < size; i++) {
        if (pre[i] < min_val || pre[i] > max_val) {
            return false;
        }
        if (pre[i] < pre[i-1]) {
            max_val = pre[i-1];
        } else {
            min_val = pre[i-1];
        }
    }
    return true;
}
 
 
// driver program to test above function
public static void main (String[] args)
{
    int pre[] = new int[]{8, 3, 5, 7, 6};
    int size = pre.length;
    if (hasOnlyOneChild(pre, size) == true )
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code has been contributed by Pushpesh Raj


Python3




# Define a function to check if a given list represents a binary tree
# with each node having at most one child.
def has_only_one_child(pre):
    # Initialize variables to represent the maximum and minimum values.
    max_val = float('inf'# Initialize max_val to positive infinity.
    min_val = float('-inf') # Initialize min_val to negative infinity.
     
    # Iterate through the elements in the list starting from the second element.
    for i in range(1, len(pre)):
        # Check if the current element is outside the valid range.
        if pre[i] < min_val or pre[i] > max_val:
            return False
         
        # Update max_val or min_val based on the relationship between
        # the current element and the previous element.
        if pre[i] < pre[i - 1]:
            max_val = pre[i - 1]
        else:
            min_val = pre[i - 1]
     
    # If the loop completes without returning False, the list represents
    # a binary tree with each node having at most one child.
    return True
 
# Driver program to test the has_only_one_child function.
if has_only_one_child([8, 3, 5, 7, 6]):
    print("Yes"# If the function returns True, print "Yes."
else:
    print("No")   # If the function returns False, print "No."
     
# This code is contributed by shivamgupta0987654321


C#




using System;
 
class Program
{
    static bool HasOnlyOneChild(int[] pre)
    {
        int maxVal = int.MaxValue, minVal = int.MinValue;
 
        for (int i = 1; i < pre.Length; i++)
        {
            if (pre[i] < minVal || pre[i] > maxVal)
            {
                return false;
            }
            if (pre[i] < pre[i - 1])
            {
                maxVal = pre[i - 1];
            }
            else
            {
                minVal = pre[i - 1];
            }
        }
        return true;
    }
 
    static void Main(string[] args)
    {
        int[] pre = { 8, 3, 5, 7, 6 };
        if (HasOnlyOneChild(pre))
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }
    }
}


Javascript




function hasOnlyOneChild(pre, size) {
    let max_val = Number.MAX_VALUE, min_val = Number.MIN_VALUE; // initialize max and min to extreme values
    for (let i = 1; i < size; i++) {
        if (pre[i] < min_val || pre[i] > max_val) {
            return false;
        }
        if (pre[i] < pre[i-1]) {
            max_val = pre[i-1];
        } else {
            min_val = pre[i-1];
        }
    }
    return true;
}
 
// driver program to test above function
let pre = [8, 3, 5, 7, 6];
let size = pre.length;
if (hasOnlyOneChild(pre, size) == true )
    console.log("Yes");
else
    console.log("No");


Output

Yes





Time complexity: O(n)

Auxiliary Space: O(n)



Last Updated : 05 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads