Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Print Levels of all nodes in a Binary Tree
Next article icon

Print all internal nodes of a Binary tree

Last Updated : 28 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary tree, the task is to print all the internal nodes in a tree. 
An internal node is a node which carries at least one child or in other words, an internal node is not a leaf node. Here we intend to print all such internal nodes in level order. Consider the following Binary Tree:
 

Input: 
 

Output: 15 10 20

 

The way to solve this involves a BFS of the tree. The algorithm is as follows: 
 

  • Do a level order traversal by pushing nodes in the queue one by one.
  • Pop the elements from the queue one by one and keep a track of following cases: 
    1. The node has a left child only.
    2. The node has a right child only.
    3. The node has both left and right child.
    4. The node has no children at all.
  • Except for case 4, print the data in the node for all the other 3 cases.

Below is the implementation of the above approach:
 

C++




// C++ program to print all internal
// nodes in tree
#include <bits/stdc++.h>
using namespace std;
 
// A node in the Binary tree
struct Node {
    int data;
    Node *left, *right;
    Node(int data)
    {
       left = right = NULL;
       this->data = data;
    }
};
 
// Function to print all internal nodes
// in level order from left to right
void printInternalNodes(Node* root)
{
    // Using a queue for a level order traversal
    queue<Node*> q;
    q.push(root);
    while (!q.empty()) {
 
        // Check and pop the element in
        // the front of the queue
        Node* curr = q.front();
        q.pop();
 
        // The variable flag keeps track of
        // whether a node is an internal node
        bool isInternal = 0;
 
        // The node has a left child
        if (curr->left) {
            isInternal = 1;
            q.push(curr->left);
        }
 
        // The node has a right child
        if (curr->right) {
            isInternal = 1;
            q.push(curr->right);
        }
 
        // In case the node has either a left
        // or right child or both print the data
        if (isInternal)
            cout << curr->data << " ";
    }
}
 
// Driver program to build a sample tree
int main()
{
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->right->left = new Node(5);
    root->right->right = new Node(6);
    root->right->right->right = new Node(10);
    root->right->right->left = new Node(7);
    root->right->left->left = new Node(8);
    root->right->left->right = new Node(9);
 
    // A call to the function
    printInternalNodes(root);
 
    return 0;
}
 
 

Java




// Java program to print all internal
// nodes in tree
import java.util.*;
class GfG
{
 
// A node in the Binary tree
static class Node
{
    int data;
    Node left, right;
    Node(int data)
    {
        left = right = null;
        this.data = data;
    }
}
 
// Function to print all internal nodes
// in level order from left to right
static void printInternalNodes(Node root)
{
    // Using a queue for a level order traversal
    Queue<Node> q = new LinkedList<Node>();
    q.add(root);
    while (!q.isEmpty())
    {
 
        // Check and pop the element in
        // the front of the queue
        Node curr = q.peek();
        q.remove();
 
        // The variable flag keeps track of
        // whether a node is an internal node
        boolean isInternal = false;
 
        // The node has a left child
        if (curr.left != null)
        {
            isInternal = true;
            q.add(curr.left);
        }
 
        // The node has a right child
        if (curr.right != null)
        {
            isInternal = true;
            q.add(curr.right);
        }
 
        // In case the node has either a left
        // or right child or both print the data
        if (isInternal == true)
            System.out.print(curr.data + " ");
    }
}
 
// Driver code
public static void main(String[] args)
{
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.right.left = new Node(5);
    root.right.right = new Node(6);
    root.right.right.right = new Node(10);
    root.right.right.left = new Node(7);
    root.right.left.left = new Node(8);
    root.right.left.right = new Node(9);
 
    // A call to the function
    printInternalNodes(root);
}
}
 
// This code is contributed by
// Prerna Saini.
 
 

Python3




# Python3 program to print all internal
# nodes in tree
 
# A node in the Binary tree
class new_Node:
     
    # Constructor to create a new_Node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
     
# Function to print all internal nodes
# in level order from left to right
def printInternalNodes(root):
     
    # Using a queue for a level order traversal
    q = []
    q.append(root)
    while (len(q)):
         
        # Check and pop the element in
        # the front of the queue
        curr = q[0]
        q.pop(0)
         
        # The variable flag keeps track of
        # whether a node is an internal node
        isInternal = 0
         
        # The node has a left child
        if (curr.left):
            isInternal = 1
            q.append(curr.left)
         
        # The node has a right child
        if (curr.right):
            isInternal = 1
            q.append(curr.right)
         
        # In case the node has either a left
        # or right child or both print the data
        if (isInternal):
            print(curr.data, end = " ")
     
# Driver Code
root = new_Node(1)
root.left = new_Node(2)
root.right = new_Node(3)
root.left.left = new_Node(4)
root.right.left = new_Node(5)
root.right.right = new_Node(6)
root.right.right.right = new_Node(10)
root.right.right.left = new_Node(7)
root.right.left.left = new_Node(8)
root.right.left.right = new_Node(9)
 
# A call to the function
printInternalNodes(root)
 
# This code is contributed by SHUBHAMSINGH10
 
 

C#




// C# program to print all internal
// nodes in tree
using System;
using System.Collections.Generic;
 
class GFG
{
 
// A node in the Binary tree
public class Node
{
    public int data;
    public Node left, right;
    public Node(int data)
    {
        left = right = null;
        this.data = data;
    }
}
 
// Function to print all internal nodes
// in level order from left to right
static void printInternalNodes(Node root)
{
    // Using a queue for a level order traversal
    Queue<Node> q = new Queue<Node>();
    q.Enqueue(root);
    while (q.Count != 0)
    {
 
        // Check and pop the element in
        // the front of the queue
        Node curr = q.Peek();
        q.Dequeue();
 
        // The variable flag keeps track of
        // whether a node is an internal node
        Boolean isInternal = false;
 
        // The node has a left child
        if (curr.left != null)
        {
            isInternal = true;
            q.Enqueue(curr.left);
        }
 
        // The node has a right child
        if (curr.right != null)
        {
            isInternal = true;
            q.Enqueue(curr.right);
        }
 
        // In case the node has either a left
        // or right child or both print the data
        if (isInternal == true)
            Console.Write(curr.data + " ");
    }
}
 
// Driver code
public static void Main(String[] args)
{
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.right.left = new Node(5);
    root.right.right = new Node(6);
    root.right.right.right = new Node(10);
    root.right.right.left = new Node(7);
    root.right.left.left = new Node(8);
    root.right.left.right = new Node(9);
 
    // A call to the function
    printInternalNodes(root);
}
}
 
// This code contributed by Rajput-Ji
 
 

Javascript




<script>
 
    // JavaScript program to print all internal nodes in tree
     
    // A node in the Binary tree
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
 
    // Function to print all internal nodes
    // in level order from left to right
    function printInternalNodes(root)
    {
        // Using a queue for a level order traversal
        let q = [];
        q.push(root);
        while (q.length > 0)
        {
 
            // Check and pop the element in
            // the front of the queue
            let curr = q[0];
            q.shift();
 
            // The variable flag keeps track of
            // whether a node is an internal node
            let isInternal = false;
 
            // The node has a left child
            if (curr.left != null)
            {
                isInternal = true;
                q.push(curr.left);
            }
 
            // The node has a right child
            if (curr.right != null)
            {
                isInternal = true;
                q.push(curr.right);
            }
 
            // In case the node has either a left
            // or right child or both print the data
            if (isInternal == true)
                document.write(curr.data + " ");
        }
    }
     
    let root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.right.left = new Node(5);
    root.right.right = new Node(6);
    root.right.right.right = new Node(10);
    root.right.right.left = new Node(7);
    root.right.left.left = new Node(8);
    root.right.left.right = new Node(9);
   
    // A call to the function
    printInternalNodes(root);
 
</script>
 
 
Output: 
1 2 3 5 6

 



Next Article
Print Levels of all nodes in a Binary Tree

C

code_freak
Improve
Article Tags :
  • Data Structures
  • DSA
  • Tree
Practice Tags :
  • Data Structures
  • Tree

Similar Reads

  • Print Levels of all nodes in a Binary Tree
    Given a Binary Tree and a key, write a function that prints levels of all keys in given binary tree. For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key
    7 min read
  • Print all full nodes in a Binary Tree
    Given a binary tree, print all nodes will are full nodes. Full Nodes are nodes which has both left and right children as non-empty. Examples: Input : 10 / \ 8 2 / \ / 3 5 7 Output : 10 8 Input : 1 / \ 2 3 / \ 4 6 Output : 1 3 This is a simple problem. We do any of the tra­ver­sals (Inorder, Pre­orde
    4 min read
  • Sum of all nodes in a binary tree
    Give an algorithm for finding the sum of all elements in a binary tree. In the above binary tree sum = 106. Recommended PracticeSum of Binary TreeTry It!The idea is to recursively, call left subtree sum, right subtree sum and add their values to current node's data. Implementation: C/C++ Code /* Pro
    15+ min read
  • Print all even nodes of Binary Search Tree
    Given a binary search tree. The task is to print all even nodes of the binary search tree. Examples: Input : 5 / \ 3 7 / \ / \ 2 4 6 8 Output : 2 4 6 8 Input : 14 / \ 12 17 / \ / \ 8 13 16 19 Output : 8 12 14 16 Approach: Traverse the Binary Search tree and check if current node's value is even. If
    8 min read
  • Print all the leaf nodes of Binary Heap
    Given an array of N elements which denotes the array representation of binary heap, the task is to find the leaf nodes of this binary heap. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 5 6 7 Explanation: 1 / \ 2 3 / \ / \ 4 5 6 7 Leaf nodes of the Binary Heap are: 4 5 6 7 Input: arr[] =
    7 min read
  • All Leaves of a Bnary Tree - Print in Order
    Given a binary tree, we need to print all leaf nodes of the given binary tree from left to right. That is, the nodes should be printed in the order they appear from left to right in the given tree.  For Example,  Input : Root of the below tree Output : 4 6 7 9 10 Corner Cases : For a tree with singl
    11 min read
  • Print all Nodes of given Binary Tree at the Kth Level
    Given a binary tree and an integer K, the task is to print all the integers at the Kth level in the tree from left to right. Examples: Input: Tree in the image below, K = 3 Output: 4 5 6Explanation: All the nodes present in level 3 of above binary tree from left to right are 4, 5, and 6. Input: Tree
    5 min read
  • Print Ancestors of a given node in Binary Tree
    Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree. For example, if the given tree is following Binary Tree and the key is 7, then your function should print 4, 2, and 1. 1 / \ 2 3 / \ 4 5 / 7Recommended PracticeAncestors in Binary TreeT
    13 min read
  • Print all nodes in a binary tree having K leaves
    Given a binary tree and a integer value K, the task is to find all nodes in given binary tree having K leaves in subtree rooted with them. Examples : // For above binary tree Input : k = 2 Output: {3} // here node 3 have k = 2 leaves Input : k = 1 Output: {6} // here node 6 have k = 1 leaveRecommend
    7 min read
  • Print cousins of a given node in Binary Tree
    Given a binary tree and a node, print all cousins of given node. Note that siblings should not be printed.Example: Input : root of below tree 1 / \ 2 3 / \ / \ 4 5 6 7 and pointer to a node say 5. Output : 6, 7 The idea to first find level of given node using the approach discussed here. Once we hav
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences