The Wayback Machine - https://web.archive.org/web/20240911091751/https://www.geeksforgeeks.org/print-left-view-binary-tree/
Open In App

Left View of a Binary Tree

Last Updated : 04 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a Binary Tree, the task is to print the left view of the Binary Tree. The left view of a Binary Tree is a set of leftmost nodes for every level.

Example 1: The Green colored nodes represents the left view in the below Binary tree.

Left-view-in-binary-Tree-2

Example 2: The Green colored nodes represents the left view in the below Binary tree.

Left-view-in-binary-Tree-4

Print Left View of a Binary Tree Using Recursion: 

Keep track of the level of a node by passing the level as a parameter to all recursive calls and also keep track of the maximum level. Whenever, we see a node whose level is more than maximum level so far, we print the node because this is the first node in its level 

Note: We traverse the left subtree before right subtree. 

Below is the implementation of the above idea.

C++
// C++ program to print left view of Binary Tree
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    struct Node *left, *right;
};

// A utility function to
// create a new Binary Tree Node
struct Node* newNode(int item)
{
    struct Node* temp
        = (struct Node*)malloc(sizeof(struct Node));
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}

// Recursive function to print
// left view of a binary tree.
void leftViewUtil(struct Node* root, int level,
                  int* max_level)
{
    // Base Case
    if (root == NULL)
        return;

    // If this is the first Node of its level
    if (*max_level < level) {
        cout << root->data << " ";
        *max_level = level;
    }

    // Recur for left subtree first,
    // then right subtree
    leftViewUtil(root->left, level + 1, max_level);
    leftViewUtil(root->right, level + 1, max_level);
}

// A wrapper over leftViewUtil()
void leftView(struct Node* root)
{
    int max_level = 0;
    leftViewUtil(root, 1, &max_level);
}

// Driver Code
int main()
{
    Node* root = newNode(10);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(7);
    root->left->right = newNode(8);
    root->right->right = newNode(15);
    root->right->left = newNode(12);
    root->right->right->left = newNode(14);

    leftView(root);

    return 0;
}
C
// C program to print left view of Binary Tree
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *left, *right;
};

// A utility function to create a new Binary Tree node
struct node* newNode(int item)
{
    struct node* temp
        = (struct node*)malloc(sizeof(struct node));
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}

// Recursive function to print left view of a binary tree.
void leftViewUtil(struct node* root, int level,
                  int* max_level)
{
    // Base Case
    if (root == NULL)
        return;

    // If this is the first node of its level
    if (*max_level < level) {
        printf("%d ", root->data);
        *max_level = level;
    }

    // Recur for left and right subtrees
    leftViewUtil(root->left, level + 1, max_level);
    leftViewUtil(root->right, level + 1, max_level);
}

// A wrapper over leftViewUtil()
void leftView(struct node* root)
{
    int max_level = 0;
    leftViewUtil(root, 1, &max_level);
}

// Driver code
int main()
{
    struct node* root = newNode(10);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(7);
    root->left->right = newNode(8);
    root->right->right = newNode(15);
    root->right->left = newNode(12);
    root->right->right->left = newNode(14);

    leftView(root);

    return 0;
}
Java
// Java program to print left view of binary tree

/* Class containing left and right child of current
node and key value*/
class Node {
    int data;
    Node left, right;

    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}

/* Class to print the left view */
class BinaryTree {
    Node root;
    static int max_level = 0;

    // recursive function to print left view
    void leftViewUtil(Node node, int level)
    {
        // Base Case
        if (node == null)
            return;

        // If this is the first node of its level
        if (max_level < level) {
            System.out.print(node.data + " ");
            max_level = level;
        }

        // Recur for left and right subtrees
        leftViewUtil(node.left, level + 1);
        leftViewUtil(node.right, level + 1);
    }

    // A wrapper over leftViewUtil()
    void leftView()
    {
        max_level = 0;
        leftViewUtil(root, 1);
    }

    /* testing for example nodes */
    public static void main(String args[])
    {
        /* creating a binary tree and entering the nodes */
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(10);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(7);
        tree.root.left.right = new Node(8);
        tree.root.right.right = new Node(15);
        tree.root.right.left = new Node(12);
        tree.root.right.right.left = new Node(14);

        tree.leftView();
    }
}
Python
# Python program to print left view of Binary Tree

# A binary tree node
class Node:

    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None


# Recursive function print left view of a binary tree
def leftViewUtil(root, level, max_level):

    # Base Case
    if root is None:
        return

    # If this is the first node of its level
    if (max_level[0] < level):
        print (root.data, end = " ")
        max_level[0] = level

    # Recur for left and right subtree
    leftViewUtil(root.left, level + 1, max_level)
    leftViewUtil(root.right, level + 1, max_level)


# A wrapper over leftViewUtil()
def leftView(root):
    max_level = [0]
    leftViewUtil(root, 1, max_level)


# Driver program to test above function
if __name__ == '__main__':
    root = Node(10)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(7)
    root.left.right = Node(8)
    root.right.right = Node(15)
    root.right.left = Node(12)
    root.right.right.left = Node(14)
    
    leftView(root)

# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
using System;

// C# program to print left view of binary tree

/* Class containing left and right child of current
node and key value*/
public class Node {
    public int data;
    public Node left, right;

    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}

/* Class to print the left view */
public class BinaryTree {
    public Node root;
    public static int max_level = 0;

    // recursive function to print left view
    public virtual void leftViewUtil(Node node, int level)
    {
        // Base Case
        if (node == null) {
            return;
        }

        // If this is the first node of its level
        if (max_level < level) {
            Console.Write(node.data + " ");
            max_level = level;
        }

        // Recur for left and right subtrees
        leftViewUtil(node.left, level + 1);
        leftViewUtil(node.right, level + 1);
    }

    // A wrapper over leftViewUtil()
    public virtual void leftView()
    {
        leftViewUtil(root, 1);
    }

    /* testing for example nodes */
    public static void Main(string[] args)
    {
        /* creating a binary tree and entering the nodes */
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(10);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(7);
        tree.root.left.right = new Node(8);
        tree.root.right.right = new Node(15);
        tree.root.right.left = new Node(12);
        tree.root.right.right.left = new Node(14);

        tree.leftView();
    }
}

// This code is contributed by Shrikant13
JavaScript
<script>
 
// Javascript program to print left view
// of binary tree

// Class containing left and right 
// child of current node and key value
class Node 
{
    constructor(item)
    {
        this.data = item;
        this.left = null;
        this.right = null;
    }
}

// Class to print the left view 
var root ;
var max_level = 0;

// Recursive function to print left view
function leftViewUtil(node, level)
{
    
    // Base Case
    if (node == null) 
    {
        return;
    }
    
    // If this is the first node of its level
    if (max_level < level)
    {
        document.write(" " + node.data);
        max_level = level;
    }
    
    // Recur for left and right subtrees
    leftViewUtil(node.left, level + 1);
    leftViewUtil(node.right, level + 1);
}

// A wrapper over leftViewUtil()
function leftView()
{
    leftViewUtil(root, 1);
}

// Driver code

// Testing for example nodes 
// Creating a binary tree and 
// entering the nodes 
root = Node(10)
root.left = new Node(2) 
root.right = new Node(3)
root.left.left = new Node(7)
root.left.right = new Node(8) 
root.right.right = new Node(15) 
root.right.left = new Node(12)
root.right.right.left = new Node(14)    


leftView();

// This code is contributed by rrrtnx

</script>

Output
10 2 7 14 

Time Complexity: O(N), The function does a simple traversal of the tree, so the complexity is O(n). 
Auxiliary Space: O(h), due to the stack space during recursive call. ‘h’ here is the height of the binary tree.

Print Left View of a Binary Tree Using Level Order Traversal: 

Below is the idea to solve the problem:

The left view contains all nodes that are the first nodes in their levels. A simple solution is to do level order traversal and print the first node in every level. 

Follow the below step to Implement the idea:

  • Do level order traversal of the tree.
    • For each level keep a track of the current level and print the first encountered node of this level.
    • Move to the next level.

Below is the implementation of the above approach:

C++
// C++ program to print left view of 
// Binary Tree 

#include<bits/stdc++.h> 
using namespace std; 

// A Binary Tree Node 
struct Node 
{ 
    int data; 
    struct Node *left, *right; 
}; 

// Utility function to create a new tree node 
Node* newNode(int data) 
{ 
    Node *temp = new Node; 
    temp->data = data; 
    temp->left = temp->right = NULL; 
    return temp; 
} 

// function to print left view of 
// binary tree 
void printLeftView(Node* root) 
{ 
    if (!root) 
        return; 

    queue<Node*> q; 
    q.push(root); 

    while (!q.empty()) 
    {     
        // number of nodes at current level 
        int n = q.size(); 
        
        // Traverse all nodes of current level 
        for(int i = 1; i <= n; i++) 
        { 
            Node* temp = q.front(); 
            q.pop(); 
                
            // Print the left most element 
            // at the level 
            if (i == 1) 
                cout<<temp->data<<" "; 
            
            // Add left node to queue 
            if (temp->left != NULL) 
                q.push(temp->left); 

            // Add right node to queue 
            if (temp->right != NULL) 
                q.push(temp->right); 
        } 
    } 
}     

// Driver code
int main() 
{ 
    // Let's construct the tree as 
    // shown in example 

    Node* root = newNode(10); 
    root->left = newNode(2); 
    root->right = newNode(3); 
    root->left->left = newNode(7); 
    root->left->right = newNode(8); 
    root->right->right = newNode(15); 
    root->right->left = newNode(12); 
    root->right->right->left = newNode(14); 

    printLeftView(root); 
} 

// This code is contributed by 
// Manne SreeCharan
Java
// Java program to print left view of Binary
// Tree
import java.util.*;

public class PrintRightView {
    // Binary tree node
    private static class Node {
        int data;
        Node left, right;

        public Node(int data)
        {
            this.data = data;
            this.left = null;
            this.right = null;
        }
    }

    // function to print left view of binary tree
    private static void printLeftView(Node root)
    {
        if (root == null)
            return;

        Queue<Node> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            // number of nodes at current level
            int n = queue.size();

            // Traverse all nodes of current level
            for (int i = 1; i <= n; i++) {
                Node temp = queue.poll();

                // Print the left most element at
                // the level
                if (i == 1)
                    System.out.print(temp.data + " ");

                // Add left node to queue
                if (temp.left != null)
                    queue.add(temp.left);

                // Add right node to queue
                if (temp.right != null)
                    queue.add(temp.right);
            }
        }
    }

    // Driver code
    public static void main(String[] args)
    {
        // construct binary tree as shown in
        // above diagram
        Node root = new Node(10);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(7);
        root.left.right = new Node(8);
        root.right.right = new Node(15);
        root.right.left = new Node(12);
        root.right.right.left = new Node(14);

        printLeftView(root);
    }
}

// This code is contributed by
// Manne SreeCharan
Python
# Python3 program to print left view of
# Binary Tree

# 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
        self.hd = 0

# function to print left view of
# binary tree


def printLeftView(root):

    if (not root):
        return

    q = []
    q.append(root)

    while (len(q)):

        # number of nodes at current level
        n = len(q)

        # Traverse all nodes of current level
        for i in range(1, n + 1):
            temp = q[0]
            q.pop(0)

            # Print the left most element
            # at the level
            if (i == 1):
                print(temp.data, end=" ")

            # Add left node to queue
            if (temp.left != None):
                q.append(temp.left)

            # Add right node to queue
            if (temp.right != None):
                q.append(temp.right)


# Driver Code
if __name__ == '__main__':

    root = newNode(10)
    root.left = newNode(2)
    root.right = newNode(3)
    root.left.left = newNode(7)
    root.left.right = newNode(8)
    root.right.right = newNode(15)
    root.right.left = newNode(12)
    root.right.right.left = newNode(14)
    printLeftView(root)

# This code is contributed by
# Manne SreeCharan
C#
// C# program to print left view
// of Binary Tree
using System;
using System.Collections.Generic;

public class PrintRightView {
    // Binary tree node
    private class Node {
        public int data;
        public Node left, right;

        public Node(int data)
        {
            this.data = data;
            this.left = null;
            this.right = null;
        }
    }

    // function to print left view of binary tree
    private static void printRightView(Node root)
    {
        if (root == null)
            return;

        Queue<Node> queue = new Queue<Node>();
        queue.Enqueue(root);

        while (queue.Count != 0) {
            // number of nodes at current level
            int n = queue.Count;

            // Traverse all nodes of current level
            for (int i = 1; i <= n; i++) {
                Node temp = queue.Dequeue();

                // Print the left most element at
                // the level
                if (i == 1)
                    Console.Write(temp.data + " ");

                // Add left node to queue
                if (temp.left != null)
                    queue.Enqueue(temp.left);

                // Add right node to queue
                if (temp.right != null)
                    queue.Enqueue(temp.right);
            }
        }
    }

    // Driver code
    public static void Main(String[] args)
    {
        // construct binary tree as shown in
        // above diagram
        Node root = new Node(10);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(7);
        root.left.right = new Node(8);
        root.right.right = new Node(15);
        root.right.left = new Node(12);
        root.right.right.left = new Node(14);
        printRightView(root);
    }
}

// This code is contributed Manne SreeCharan
JavaScript
<script>

// JavaScript program to print left view of
// Binary Tree
class newNode{

    // Construct to create a newNode
    constructor(key){
        this.data = key
        this.left = null
        this.right = null
        this.hd = 0
    }
}

// function to print left view of
// binary tree
function printLeftView(root){

    if (root == null)
        return

    let q = []
    q.push(root)

    while (q.length){

        // number of nodes at current level
        let n = q.length

        // Traverse all nodes of current level
        for(let i=1;i< n + 1;i++){
            let temp = q.shift()

            // Print the left most element
            // at the level
            if (i == 1)
                document.write(temp.data," ")

            // Add left node to queue
            if (temp.left != null)
                q.push(temp.left)

            // Add right node to queue
            if (temp.right != null)
                q.push(temp.right)
        }
    }
}

// Driver Code
let root = new newNode(10)
root.left = new newNode(2)
root.right = new newNode(3)
root.left.left = new newNode(7)
root.left.right = new newNode(8)
root.right.right = new newNode(15)
root.right.left = new newNode(12)
root.right.right.left = new newNode(14)
printLeftView(root)

// This code is contributed by shinjanpatra

</script>

Output
10 2 7 14 

Time Complexity: O(N), where n is the number of nodes in the binary tree.
Auxiliary Space: O(N) since using space for auxiliary queue

Print Left View of a Binary Tree Using queue and a null pointer:

Below is the idea to solve the problem:

Use queue and a null pointer to mark the first element of each level. Insert a null pointer in the first and as the null pointer is reached mark bool as true and take the next element as left view element.

Below is the Implementation of the above approach:

C++
// C++ Code for the above iterative approach
#include <bits/stdc++.h>
using namespace std;

//  Tree Node Structure contains data, left and right
//  pointer
struct Node {
    int data;
    struct Node *left, *right;
};

// A utility function to
// create a new Binary Tree Node
struct Node* newNode(int item)
{
    struct Node* temp
        = (struct Node*)malloc(sizeof(struct Node));
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}

// function to get the left view of binary tree in vector
vector<int> leftView(Node* root)
{

    // store the left view
    vector<int> ans;

    // Base Case : Empty Tree
    if (!root) 
        return ans;
    

    // Create an empty queue and enque root node and null
    queue<Node*> q;
    q.push(root);
    q.push(NULL);
    bool ok = true;

    // Traverse till queue is not empty
    while (!q.empty()) {
        // get the front node and dequeue it from queue
        auto it = q.front();
        q.pop();

        // if the front node is null do following steps
        if (it == NULL) {
            if (ok == false) 
                ok = true;
            

            if (q.size() == 0) 
                break;
            
            else 
                q.push(NULL);
            
        }
        // else do the following steps
        else {
            if (ok) {
                ans.push_back(it->data);
                ok = false;
            }

            if (it->left) 
                q.push(it->left);
            
            if (it->right) 
                q.push(it->right);
            
        }
    }

    // return the left view
    return ans;
}

// driver code to test above code on a test case
int main()
{
    /*
    Input :
                   10
                 /    \
                2      3
               / \    / \
              7   8  12  15
                         /
                        14

     Output : 10 2 7 14
  */
    // let's build above shown tree
    Node* root = newNode(10);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(7);
    root->left->right = newNode(8);
    root->right->right = newNode(15);
    root->right->left = newNode(12);
    root->right->right->left = newNode(14);

    // call leftview function and store output in vec
    vector<int> vec = leftView(root);
    // traverse on left view and print each element
    for (int x : vec)
        cout << x << " ";
    cout << endl;

    return 0;
}

// This code is updated by Tapesh(tapeshdua420)
Java
// Java Program to print the left view
import java.util.*;

class GFG {
    // Binary Tree Node
    static class Node {
        int data;
        Node left, right;

        public Node(int item)
        {
            data = item;
            left = right = null;
        }
    };
    // function to print the left view of binary tree
    public static ArrayList<Integer> leftView(Node root)
    {
        // Your code here
        ArrayList<Integer> ans = new ArrayList<>();

        if (root == null) {
            return ans;
        }

        Queue<Node> q = new LinkedList<>();
        q.add(root);
        q.add(null);
        boolean ok = true;

        while (!q.isEmpty()) {
            Node it = q.poll();
            if (it == null) {
                if (ok == false) {
                    ok = true;
                }

                if (q.size() == 0)
                    break;

                else {
                    q.add(null);
                }
            }
            else {

                if (ok) {
                    ans.add(it.data);
                    ok = false;
                }

                if (it.left != null) {
                    q.add(it.left);
                }

                if (it.right != null) {
                    q.add(it.right);
                }
            }
        }

        return ans;
    }
    // driver code
    public static void main(String[] args)
    {
        Node root = new Node(10);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(7);
        root.left.right = new Node(8);
        root.right.right = new Node(15);
        root.right.left = new Node(12);
        root.right.right.left = new Node(14);

        ArrayList<Integer> vec = leftView(root);
        for (int x : vec) {
            System.out.print(x + " ");
        }
        System.out.println();
    }
}

// This code is contributed by Tapesh(tapeshdua420)
Python
# Python Program to print left view

# Tree Node Class
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# function to get the left view of binary tree
def leftView(root):
    ans = []

    if not root:
        return ans

    q = []
    q.append(root)
    q.append(None)
    ok = True

    while len(q) != 0:
        it = q[0]
        del q[0]
        if it == None:
            if ok == False:
                ok = True
            if len(q) == 0:
                break

            else:
                q.append(None)

        else:
            if ok:
                ans.append(it.data)
                ok = False

            if it.left != None:
                q.append(it.left)
            if it.right != None:
                q.append(it.right)

    return ans


# Driver Code
if __name__ == '__main__':
    root = Node(10)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(7)
    root.left.right = Node(8)
    root.right.right = Node(15)
    root.right.left = Node(12)
    root.right.right.left = Node(14)

    vec = leftView(root)

    # print the left view
    for x in vec:
        print(x, end=" ")
    print()

# This code is contributed by Tapesh(tapeshdua420)
C#
// C# program to print the left view of binary tree
using System;
using System.Collections.Generic;

class GFG {
    // Binary Tree Node
    public class Node {
        public int data;
        public Node left, right;

        public Node(int item)
        {
            data = item;
            left = right = null;
        }
    };
    // function to print the left view of binary tree
    public static List<int> leftView(Node root)
    {
        // Your code here
        List<int> ans = new List<int>();
        if (root == null) {
            return ans;
        }
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);
        q.Enqueue(null);
        bool ok = true;
        while (q.Count != 0) {
            Node it = q.Dequeue();
            if (it == null) {
                if (ok == false) {
                    ok = true;
                }
                if (q.Count == 0)
                    break;
                else {
                    q.Enqueue(null);
                }
            }
            else {
                if (ok) {
                    ans.Add(it.data);
                    ok = false;
                }
                if (it.left != null) {
                    q.Enqueue(it.left);
                }
                if (it.right != null) {
                    q.Enqueue(it.right);
                }
            }
        }
        return ans;
    }
    // driver code
    public static void Main()
    {
        Node root = new Node(10);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(7);
        root.left.right = new Node(8);
        root.right.right = new Node(15);
        root.right.left = new Node(12);
        root.right.right.left = new Node(14);
        List<int> vec = leftView(root);
        foreach(var x in vec) Console.Write(x + " ");
        Console.WriteLine();
    }
}

// This code is contributed by Tapesh(tapeshdua420)
JavaScript
// JavaScript program to print left view of
// Binary Tree
class Node{
    // Construct to create a newNode
    constructor(key){
        this.data = key
        this.left = null
        this.right = null
    }
}

// function to print left view of
// binary tree
function leftView(root){
    // store the left view
    ans = []
    
    // Base Case : Empty Tree
    if (root == null)
        return ans
    
    // Create an empty queue and enqueue root node and null
    let q = []
    q.push(root)
    q.push(null)
    let ok = true
    while (q.length){
        // get the front node and dequeue it from queue
        let it = q.shift()
        
        // if the front node is null do following steps
        if(it == null){
            if(ok == false){
                ok = true
            }
            
            if(q.length == 0){
                break
            }
            else{
                q.push(null)
            }
        }
        // else do the following steps
        else{
            if(ok){
                ans.push(it.data)
                ok = false
            }
            if(it.left != null){
                q.push(it.left)
            }
            if(it.right != null){
                q.push(it.right)
            }
        }
    }
    
    // return the left view
    return ans
}

// Driver Code
/*
    Input :
                   10
                 /    \
                2      3
               / \    / \
              7   8  12  15
                         /
                        14
 
     Output : 10 2 7 14
  */
let root = new Node(10)
root.left = new Node(2)
root.right = new Node(3)
root.left.left = new Node(7)
root.left.right = new Node(8)
root.right.right = new Node(15)
root.right.left = new Node(12)
root.right.right.left = new Node(14)
let vec = leftView(root)
for(let i = 0; i<vec.length; i++){
    document.write(vec[i]);
}

// This code is contributed by Yash Agarwal(yashagarwal2852002)

Output
10 2 7 14 

Time Complexity: O(N) where N is the total number of nodes.
Auxiliary Space: O(N) due to the space occupied by queue.



Similar Reads

Iterative Method To Print Left View of a Binary Tree
Given a Binary Tree, print it's left view. Left view of a Binary Tree is a set of nodes visible when tree is seen from the left side . Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 1 2 4 Input : 1 / \ 2 3 \ / 4 5 \ 6 / \ 7 8 Output : 1 2 4 6 7 We have already discussed this problem using the Recursion method, here iterative approach is used
13 min read
Sum of nodes in the left view of the given binary tree
Given a binary tree, the task is to find the sum of the nodes which are visible in the left view. The left view of a binary tree is the set of nodes visible when the tree is viewed from the left.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 7 1 + 2 + 4 = 7 Input: 1 / \ 2 3 \ 4 \ 5 \ 6 Output: 18 Approach: The problem can be solved using simple rec
9 min read
Check if the Left View of the given tree is sorted or not
Given a tree, our task is to check whether its left view is sorted or not. If it is then return true else false. Examples: Input: Output: true Explanation: The left view for the tree would be 10, 20, 50 which is in sorted order. Approach:To solve the problem mentioned above we have to perform level order traversal on the tree and look for the very
9 min read
Left and Right view of a Generic Tree
Given a Generic Tree consisting of N nodes, the task is to find the left and right views of the given generic Tree. Examples: Input: 1 / \ 2 3 / \ / \ \4 5 6 7 8 Output:Left View: 1 2 4 Right View: 1 3 8 Explanation:When the tree is viewed from the left side, then the nodes which are visible is 1 2 4.When the tree is viewed from the right side, the
9 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Print nodes in the Top View of Binary Tree | Set 3
Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes can be printed in any order. Expected time complexity is O(n) A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance of left child of a node x is eq
9 min read
Sum of nodes in top view of binary tree
Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, the task is to print the sum of nodes in top view.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 16 Input: 1 / \ 2 3 \ 4 \ 5 \ 6 Output: 12 Approach: The idea is to put nodes of same horizontal distance together. We do a level order trav
13 min read
Print Bottom-Right View of a Binary Tree
Given a Binary Tree, print Bottom-Right view of it. The Bottom Right view of a Binary Tree is a set of nodes visible when the tree is visited from Bottom Right side, return the values of the nodes ordered from right to left. In the bottom-right view, on viewing the tree at an angle of 45 degrees from the bottom-right side and only a few nodes would
11 min read
Check if Nodes in Top view of a Binary Tree forms a Palindrome Number or not
Given a binary tree consisting of N nodes, the task is to check if the nodes in the top view of a Binary Tree forms a palindrome number or not. If found to be a palindrome, then print "Yes". Otherwise, print "No". Examples: Input: 5 / \ 3 3 / \ \ 6 2 6Output: YesExplanation:Nodes in the top view are {6, 3, 5, 3, 6}. Hence, the generated number ( =
10 min read
Minimum nodes for same right view in Binary tree
Given a binary tree where each node contains a positive integer, the task is to find the minimum number of nodes that need to be removed from the tree, such that the resulting tree has the same right view as the original tree. Examples: Input: 1 / \ 2 3 \ \ 8 5 \ 6 Output: 2Explanation: The right view of the given binary tree is [1, 3, 5, 6]. If we
11 min read
Print Nodes in Top View of Binary Tree
The top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes can be printed in any order. A node x is there in the output if x is the topmost node at its horizontal distance. The horizontal distance of the left child of a node x is equal to a horizont
15+ min read
Sum of nodes in bottom view of Binary Tree
Given a binary tree, the task is to print the sum of nodes in the bottom view of the given Binary Tree. The bottom view of a binary tree is the set of nodes visible when the tree is viewed from the bottom. Examples: Input : 1 / \ 2 3 / \ \ 4 5 6Output : 20Input : 1 / \ 2 3 \ 4 \ 5 \ 6Output : 17Approach: The idea is to use a queue. Put tree nodes i
15+ min read
Right view of Binary Tree using Queue
Given a Binary Tree, print Right view of it. Right view of a Binary Tree is set of nodes visible when tree is visited from Right side. Examples: Input : 10 / \ 2 3 / \ / \ 7 8 12 15 / 14 Output : 10 3 15 14 The output nodes are the rightmost nodes of their respective levels. We have already discussed recursive solution for right view. In this post,
6 min read
Sum of nodes in the right view of the given binary tree
Given a binary tree, the task is to find the sum of the nodes which are visible in the right view. The right view of a binary tree is the set of nodes visible when the tree is viewed from the right.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6Output: 101 + 3 + 6 = 10Input: 1 / \ 2 3 \ 4 \ 5 \ 6Output: 19Approach: The problem can be solved using simple rec
15+ min read
Bottom View of a Binary Tree
Given a Binary Tree, The task is to print the bottom view from left to right. A node x is there in output if x is the bottommost node at its horizontal distance. The horizontal distance of the left child of a node x is equal to a horizontal distance of x minus 1, and that of a right child is the horizontal distance of x plus 1. Examples: Input: 20
15+ min read
Print Right View of a Binary Tree
Given a Binary Tree, print the Right view of it. The right view of a Binary Tree is a set of nodes visible when the tree is visited from the Right side. Examples: Example 1: The Green colored nodes (1, 3, 5) represents the Right view in the below Binary tree. Example 2: The Green colored nodes (1, 3, 4, 5) represents the Right view in the below Bin
15+ min read
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
Print a matrix in alternate manner (left to right then right to left)
Given a 2D array, the task is to print the 2D in alternate manner (First row from left to right, then from right to left, and so on). Examples: Input : arr[][2] = {{1, 2} {2, 3}}; Output : 1 2 3 2 Input :arr[][3] = { { 7 , 2 , 3 }, { 2 , 3 , 4 }, { 5 , 6 , 1 }}; Output : 7 2 3 4 3 2 5 6 1 The solution of this problem is that run two loops and print
5 min read
Deepest left leaf node in a binary tree
Given a Binary Tree, find the deepest leaf node that is left child of its parent. For example, consider the following tree. The deepest left leaf node is the node with value 9. 1 / \ 2 3 / / \ 4 5 6 \ \ 7 8 / \ 9 10 The idea is to recursively traverse the given binary tree and while traversing, maintain “level” which will store the current node’s l
13 min read
Convert left-right representation of a binary tree to down-right
Left-Right representation of a binary tree is standard representation where every node has a pointer to left child and another pointer to right child.Down-Right representation is an alternate representation where every node has a pointer to left (or first) child and another pointer to next sibling. So siblings at every level are connected from left
10 min read
Deepest left leaf node in a binary tree | iterative approach
Given a Binary Tree, find the deepest leaf node that is left child of its parent. For example, consider the following tree. The deepest left leaf node is the node with value 9. Examples: Input : 1 / \ 2 3 / / \ 4 5 6 \ \ 7 8 / \ 9 10 Output : 9 Recursive approach to this problem is discussed hereFor iterative approach, idea is similar to Method 2 o
8 min read
Get maximum left node in binary tree
Given a tree, the task is to find the maximum in an only left node of the binary tree. Examples: Input : 7 / \ 6 5 / \ / \ 4 3 2 1 Output : 6 Input : 1 / \ 2 3 / / \ 4 5 6 \ / \ 7 8 9 Output : 8 Traverse with inorder traversal and Apply the condition for the left node only and get maximum of left node. Implementation: Let's try to understand with c
10 min read
Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
Given a Binary Tree, the task is to print the leaf nodes from left to right. The nodes must be printed in the order they appear from left to right.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output :4 5 6 7 Input : 4 / \ 5 9 / \ / \ 8 3 7 2 / / \ 12 6 1 Output :12 3 7 6 1 We have already discussed the Recursive approach. Here we will solve the prob
8 min read
Print all leaf nodes of a binary tree from right to left
Given a binary tree, the task is to print all the leaf nodes of the binary tree from right to left. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 7 6 5 4 Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output : 9 8 7 4 Recursive Approach: Traverse the tree in Preorder fashion, by first processing the root, then right subtree and then left subtree
14 min read
Count smaller elements on right side and greater elements on left side using Binary Index Tree
Given an array arr[] of size N. The task is to find smaller elements on the right side and greater elements on the left side for each element arr[i] in the given array. Examples: Input: arr[] = {12, 1, 2, 3, 0, 11, 4} Output: Smaller right: 6 1 1 1 0 1 0 Greater left: 0 1 1 1 4 1 2 Input: arr[] = {5, 4, 3, 2, 1} Output: Smaller right: 4 3 2 1 0 Gre
15+ min read
Print left and right leaf nodes separately in Binary Tree
Given a binary tree, the task is to print left and right leaf nodes separately. Examples: Input: 0 / \ 1 2 / \ 3 4 Output: Left Leaf Nodes: 3 Right Leaf Nodes: 4 2 Input: 0 \ 1 \ 2 \ 3 Output: Left Leaf Nodes: None Right Leaf Nodes: 3 Approach: Check if given node is null. If null, then return from the function.For each traversal at right and left,
8 min read
Bottom-left to upward-right Traversal in a Binary Tree
Given a Binary Tree, the task is to print the Bottom-left to Upward-right Traversal of the given Binary Tree i.e., the level order traversal having level as Bottom-left to Upward-right node. Examples: Input: Below is the given Tree: Output: 2 7 2 5 6 5 11 4 9Explanation: Level 1: 2 7 2 (going upwards from bottom left to right to root) Level 2: 5 6
15 min read
Left rotate digits of node values of all levels of a Binary Tree in increasing order
Given a Binary Tree, the task is to modify the Tree by left rotating every node any number of times such that every level consists of node values in increasing order from left to right. If it is not possible to arrange node values of any level in increasing order, then print "-1". Examples: Input: 341 / \ 241 123 / \ \ 324 235 161Output: 341 / \ 12
14 min read
Convert a Binary Tree to BST by left shifting digits of node values
Given a Binary Tree of positive integers. The task is to convert it to a BST using left shift operations on the digits of the nodes. If it is not possible to convert the binary tree to BST then print -1. Examples: Input: 443 / \ 132 543 / \ 343 237 Output: 344 / \ 132 435 / \ 433 723 Explanation: 443 ? left shift two times ? 344 132 ? zero shift op
12 min read
Sum of nodes in a binary tree having only the left child nodes
Given a binary tree, the task is to find the sum of binary tree nodes having only the left child nodes. Example: Input: 8 / \ 3 7 / \ / 5 6 0 / / 1 2Output: 18 Explanation: Nodes with values 5, 6, and 7 are the ones that have only the left child nodes Input: 2 / \ 3 1 / / 5 6Output: 4 Approach: The given problem can be solved by traversing the bina
6 min read