The Wayback Machine - https://web.archive.org/web/20240924154158/https://www.geeksforgeeks.org/find-first-non-matching-leaves-two-binary-trees/
Open In App

Find first non matching leaves in two binary trees

Last Updated : 21 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two binary trees, find the first leaves of two trees that do not match. If there are no non-matching leaves, print nothing.

Examples: 

Input : First Tree
          5
        /   \
       2     7
     /   \
   10     11

      Second Tree   
          6
       /    \
     10     15

Output : 11 15
If we consider leaves of two trees in order,
we can see that 11 and 15 are the first leaves 
that do not match.

Method 1 (Simple) : 
Do Inorder traversal of both trees one by one, store the leaves of both trees in two different lists. Finally, find first values which are different in both lists. Time complexity is O(n1 + n2) where n1 and n2 are number of nodes in two trees. Auxiliary space requirement is O(n1 + n2).

C++




// C++ program to find first leaves that are
// not same.
#include<bits/stdc++.h>
using namespace std;
 
// Tree node
struct Node{
    int data;
    Node *left, *right;
};
 
// Utility method to create a new node
Node *newNode(int x){
    Node * temp = new Node;
    temp->data = x;
    temp->left = temp->right = NULL;
    return temp;
}
 
// function to store leaf nodes in
// inorder fashion
void inorder(Node* root, vector<int> &list;){
    if(root == NULL) return;
    inorder(root->left, list);
    if(root->left == NULL && root->right == NULL){
        list.push_back(root->data);
    }
    inorder(root->right, list);
}
 
// Prints the first non-matching leaf node in
// two trees if it exists, else prints nothing.
void findFirstUnmatch(Node *root1, Node *root2){
    vector<int> list1, list2;
    inorder(root1, list1);
    inorder(root2, list2);
    int n = min(list1.size(), list2.size());
    for(int i = 0; i<n; i++){
        if(list1[i] != list2[i]){
            cout<<"First non matching leaves: "<<list1[i]<<" "<<list2[i]<<endl;
            return;
        }
    }
}
 
// Driver code
int main(){
    struct Node *root1 = newNode(5);
    root1->left = newNode(2);
    root1->right = newNode(7);
    root1->left->left = newNode(10);
    root1->left->right = newNode(11);
 
    struct Node * root2 = newNode(6);
    root2->left = newNode(10);
    root2->right = newNode(15);
 
    findFirstUnmatch(root1,root2);
 
    return 0;
}
 
// this code is contributed by Yash Agarwal(yashagarwal2852002)


Java




// Java program to find first leaves that are not same.
import java.util.*;
 
// Tree node
class Node {
    int data;
    Node left, right;
 
    // constructor
    Node(int item) {
        data = item;
        left = right = null;
    }
}
 
// Main class
public class Main {
    // Utility method to store leaf nodes in inorder fashion
    static void inorder(Node root, List<Integer> list) {
        if (root == null) return;
        inorder(root.left, list);
        if (root.left == null && root.right == null) {
            list.add(root.data);
        }
        inorder(root.right, list);
    }
 
    // Prints the first non-matching leaf node in two trees if it exists, else prints nothing.
    static void findFirstUnmatch(Node root1, Node root2) {
        List<Integer> list1 = new ArrayList<Integer>();
        List<Integer> list2 = new ArrayList<Integer>();
        inorder(root1, list1);
        inorder(root2, list2);
        int n = Math.min(list1.size(), list2.size());
        for (int i = 0; i < n; i++) {
            if (list1.get(i) != list2.get(i)) {
                System.out.println("First non matching leaves: " + list1.get(i) + " " + list2.get(i));
                return;
            }
        }
    }
 
    // Driver code
    public static void main(String[] args) {
        Node root1 = new Node(5);
        root1.left = new Node(2);
        root1.right = new Node(7);
        root1.left.left = new Node(10);
        root1.left.right = new Node(11);
 
        Node root2 = new Node(6);
        root2.left = new Node(10);
        root2.right = new Node(15);
 
        findFirstUnmatch(root1, root2);
    }
}


Python3




# Python program to find first leaves that are
# not same.
import sys
 
# Tree node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# function to store leaf nodes in
# inorder fashion
def inorder(root, lst):
    if not root:
        return
    inorder(root.left, lst)
    if not root.left and not root.right:
        lst.append(root.data)
    inorder(root.right, lst)
 
# Prints the first non-matching leaf node in
# two trees if it exists, else prints nothing.
def findFirstUnmatch(root1, root2):
    lst1, lst2 = [], []
    inorder(root1, lst1)
    inorder(root2, lst2)
    n = min(len(lst1), len(lst2))
    for i in range(n):
        if lst1[i] != lst2[i]:
            print(f"First non-matching leaves: {lst1[i]} {lst2[i]}")
            return
 
# Driver code
if __name__ == '__main__':
    root1 = Node(5)
    root1.left = Node(2)
    root1.right = Node(7)
    root1.left.left = Node(10)
    root1.left.right = Node(11)
 
    root2 = Node(6)
    root2.left = Node(10)
    root2.right = Node(15)
 
    findFirstUnmatch(root1,root2)


Javascript




// JavaScript program to find first leaves that are
// not same
// tree node
class Node{
    constructor(data){
        this.data = data;
        this.left = this.right = null;
    }
}
 
// utility function to create a new node
function newNode(x){
    return new Node(x);
}
 
// function to store leaf nodes in
// inorder fashion
function inorder(root, list){
    if(root == null) return;
    inorder(root.left, list);
    if(root.left == null && root.right == null) list.push(root.data);
    inorder(root.right, list);
}
 
// Prints the first non-matching leaf node in
// two trees if it exists, else prints nothing.
function findFirstUnmatch(root1, root2){
    let list1 = [];
    let list2 = [];
    inorder(root1, list1);
    inorder(root2, list2);
     
    let n = Math.min(list1.length, list2.length);
    for(let i = 0; i<n; i++){
        if(list1[i] != list2[i]){
            console.log("First non matching leaves : " + list1[i] + " " + list2[i]);
            return;
        }
    }
}
 
// driver code
let root1 = newNode(5);
root1.left = newNode(2);
root1.right = newNode(7);
root1.left.left = newNode(10);
root1.left.right = newNode(11);
 
let root2 = newNode(6);
root2.left = newNode(10);
root2.right = newNode(15);
 
findFirstUnmatch(root1, root2);


C#




using System;
using System.Collections.Generic;
 
// Tree node
public class Node {
    public int data;
    public Node left, right;
 
    public Node(int x) {
        data = x;
        left = right = null;
    }
}
 
public class Program {
    // Utility method to create a new node
    static Node NewNode(int x) {
        Node temp = new Node(x);
        return temp;
    }
 
    // function to store leaf nodes in
    // inorder fashion
    static void Inorder(Node root, List<int> list) {
        if (root == null) return;
        Inorder(root.left, list);
        if (root.left == null && root.right == null) {
            list.Add(root.data);
        }
        Inorder(root.right, list);
    }
 
    // Prints the first non-matching leaf node in
    // two trees if it exists, else prints nothing.
    static void FindFirstUnmatch(Node root1, Node root2) {
        List<int> list1 = new List<int>();
        List<int> list2 = new List<int>();
        Inorder(root1, list1);
        Inorder(root2, list2);
        int n = Math.Min(list1.Count, list2.Count);
        for (int i = 0; i < n; i++) {
            if (list1[i] != list2[i]) {
                Console.WriteLine("First non matching leaves: " + list1[i] + " " + list2[i]);
                return;
            }
        }
    }
 
    // Driver code
    static void Main() {
        Node root1 = NewNode(5);
        root1.left = NewNode(2);
        root1.right = NewNode(7);
        root1.left.left = NewNode(10);
        root1.left.right = NewNode(11);
 
        Node root2 = NewNode(6);
        root2.left = NewNode(10);
        root2.right = NewNode(15);
 
        FindFirstUnmatch(root1, root2);
    }
}


Output

First non matching leaves: 11 15

Method 2 (Efficient):
This solution auxiliary space requirement as O(h1 + h2) where h1 and h2 are heights of trees. We do Iterative Preorder traversal of both the trees simultaneously using stacks. We maintain a stack for each tree. For every tree, keep pushing nodes in the stack till the top node is a leaf node. Compare the two top nodes f both the stack. If they are equal, do further traversal else return. 

Implementation:

C++




// C++ program to find first leaves that are
// not same.
#include<bits/stdc++.h>
using namespace std;
 
// Tree node
struct Node
{
    int data;
    Node *left,  *right;
};
 
// Utility method to create a new node
Node *newNode(int x)
{
    Node * temp = new Node;
    temp->data = x;
    temp->left = temp->right = NULL;
    return temp;
}
 
bool isLeaf(Node * t)
{
    return ((t->left == NULL) && (t->right == NULL));
}
 
// Prints the first non-matching leaf node in
// two trees if it exists, else prints nothing.
void findFirstUnmatch(Node *root1, Node *root2)
{
    // If any of the tree is empty
    if (root1 == NULL || root2 == NULL)
      return;
 
    // Create two stacks for preorder traversals
    stack<Node*> s1, s2;
    s1.push(root1);
    s2.push(root2);
 
    while (!s1.empty() || !s2.empty())
    {
        // If traversal of one tree is over
        // and other tree still has nodes.
        if (s1.empty() || s2.empty() )
           return;
 
        // Do iterative traversal of first tree
        // and find first lead node in it as "temp1"
        Node *temp1 = s1.top();
        s1.pop();
        while (temp1 && !isLeaf(temp1))
        {
            // pushing right childfirst so that
            // left child comes first while popping.
            s1.push(temp1->right);
            s1.push(temp1->left);
            temp1 = s1.top();
            s1.pop();
        }
 
        // Do iterative traversal of second tree
        // and find first lead node in it as "temp2"
        Node * temp2 = s2.top();
        s2.pop();
        while (temp2 && !isLeaf(temp2))
        {
            s2.push(temp2->right);
            s2.push(temp2->left);
            temp2 = s2.top();
            s2.pop();
        }
 
        // If we found leaves in both trees
        if (temp1 != NULL && temp2 != NULL )
        {
            if (temp1->data != temp2->data )
            {
                cout << "First non matching leaves : "
                     << temp1->data <<"  "<< temp2->data
                     << endl;
                return;
            }
        }
    }
}
 
// Driver code
int main()
{
    struct Node *root1 = newNode(5);
    root1->left = newNode(2);
    root1->right = newNode(7);
    root1->left->left = newNode(10);
    root1->left->right = newNode(11);
 
    struct Node * root2 = newNode(6);
    root2->left = newNode(10);
    root2->right = newNode(15);
 
    findFirstUnmatch(root1,root2);
 
    return 0;
}


Java




// Java program to find first leaves that are
// not same.
import java.util.*;
class GfG {
 
// Tree node
static class Node
{
    int data;
    Node left, right;
}
 
// Utility method to create a new node
static Node newNode(int x)
{
    Node temp = new Node();
    temp.data = x;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
static boolean isLeaf(Node t)
{
    return ((t.left == null) && (t.right == null));
}
 
// Prints the first non-matching leaf node in
// two trees if it exists, else prints nothing.
static void findFirstUnmatch(Node root1, Node root2)
{
    // If any of the tree is empty
    if (root1 == null || root2 == null)
    return;
 
    // Create two stacks for preorder traversals
    Stack<Node> s1 = new Stack<Node> ();
    Stack<Node> s2 = new Stack<Node> ();
    s1.push(root1);
    s2.push(root2);
 
    while (!s1.isEmpty() || !s2.isEmpty())
    {
        // If traversal of one tree is over
        // and other tree still has nodes.
        if (s1.isEmpty() || s2.isEmpty() )
        return;
 
        // Do iterative traversal of first tree
        // and find first lead node in it as "temp1"
        Node temp1 = s1.peek();
        s1.pop();
        while (temp1 != null && isLeaf(temp1) != true)
        {
            // pushing right childfirst so that
            // left child comes first while popping.
            s1.push(temp1.right);
            s1.push(temp1.left);
            temp1 = s1.peek();
            s1.pop();
        }
 
        // Do iterative traversal of second tree
        // and find first lead node in it as "temp2"
        Node temp2 = s2.peek();
        s2.pop();
        while (temp2 != null && isLeaf(temp2) != true)
        {
            s2.push(temp2.right);
            s2.push(temp2.left);
            temp2 = s2.peek();
            s2.pop();
        }
 
        // If we found leaves in both trees
        if (temp1 != null && temp2 != null )
        {
            if (temp1.data != temp2.data )
            {
                System.out.println(temp1.data+" "+temp2.data);
                return;
            }
        }
    }
}
 
// Driver code
public static void main(String[] args)
{
    Node root1 = newNode(5);
    root1.left = newNode(2);
    root1.right = newNode(7);
    root1.left.left = newNode(10);
    root1.left.right = newNode(11);
 
    Node root2 = newNode(6);
    root2.left = newNode(10);
    root2.right = newNode(15);
 
    findFirstUnmatch(root1,root2);
 
}
}


Python3




# Python3 program to find first leaves
# that are not same.
 
# Tree Node
# Utility function to create a
# new tree Node
class newNode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
         
def isLeaf(t):
 
    return ((t.left == None) and
            (t.right == None))
 
# Prints the first non-matching leaf node in
# two trees if it exists, else prints nothing.
def findFirstUnmatch(root1, root2) :
 
    # If any of the tree is empty
    if (root1 == None or root2 == None) :
        return
 
    # Create two stacks for preorder
    # traversals
    s1 = []
    s2 = []
    s1.insert(0, root1)
    s2.insert(0, root2)
 
    while (len(s1) or len(s2)) :
     
        # If traversal of one tree is over
        # and other tree still has nodes.
        if (len(s1) == 0 or len(s2) == 0) :
            return
 
        # Do iterative traversal of first
        # tree and find first lead node
        # in it as "temp1"
        temp1 = s1[0]
        s1.pop(0)
        while (temp1 and not isLeaf(temp1)) :
         
            # pushing right childfirst so that
            # left child comes first while popping.
            s1.insert(0, temp1.right)
            s1.insert(0, temp1.left)
            temp1 = s1[0]
            s1.pop(0)
         
        # Do iterative traversal of second tree
        # and find first lead node in it as "temp2"
        temp2 = s2[0]
        s2.pop(0)
        while (temp2 and not isLeaf(temp2)) :
         
            s2.insert(0, temp2.right)
            s2.insert(0, temp2.left)
            temp2 = s2[0]
            s2.pop(0)
         
        # If we found leaves in both trees
        if (temp1 != None and temp2 != None ) :
         
            if (temp1.data != temp2.data ) :
             
                print("First non matching leaves :",
                        temp1.data, "", temp2.data )
                return
 
# Driver Code
if __name__ == '__main__':
    root1 = newNode(5)
    root1.left = newNode(2)
    root1.right = newNode(7)
    root1.left.left = newNode(10)
    root1.left.right = newNode(11)
 
    root2 = newNode(6)
    root2.left = newNode(10)
    root2.right = newNode(15)
 
    findFirstUnmatch(root1,root2)
 
# This code is contributed by
# SHUBHAMSINGH10


C#




// C# program to find first leaves that are
// not same.
using System;
using System.Collections.Generic;
 
class GfG
{
 
    // Tree node
    public class Node
    {
        public int data;
        public Node left, right;
    }
 
    // Utility method to create a new node
    static Node newNode(int x)
    {
        Node temp = new Node();
        temp.data = x;
        temp.left = null;
        temp.right = null;
        return temp;
    }
 
    static bool isLeaf(Node t)
    {
        return ((t.left == null) && (t.right == null));
    }
 
    // Prints the first non-matching leaf node in
    // two trees if it exists, else prints nothing.
    static void findFirstUnmatch(Node root1, Node root2)
    {
        // If any of the tree is empty
        if (root1 == null || root2 == null)
        return;
 
        // Create two stacks for preorder traversals
        Stack<Node> s1 = new Stack<Node> ();
        Stack<Node> s2 = new Stack<Node> ();
        s1.Push(root1);
        s2.Push(root2);
 
        while (s1.Count != 0 || s2.Count != 0)
        {
            // If traversal of one tree is over
            // and other tree still has nodes.
            if (s1.Count == 0 || s2.Count == 0 )
            return;
 
            // Do iterative traversal of first tree
            // and find first lead node in it as "temp1"
            Node temp1 = s1.Peek();
            s1.Pop();
            while (temp1 != null && isLeaf(temp1) != true)
            {
                // pushing right childfirst so that
                // left child comes first while popping.
                s1.Push(temp1.right);
                s1.Push(temp1.left);
                temp1 = s1.Peek();
                s1.Pop();
            }
 
            // Do iterative traversal of second tree
            // and find first lead node in it as "temp2"
            Node temp2 = s2.Peek();
            s2.Pop();
            while (temp2 != null && isLeaf(temp2) != true)
            {
                s2.Push(temp2.right);
                s2.Push(temp2.left);
                temp2 = s2.Peek();
                s2.Pop();
            }
 
            // If we found leaves in both trees
            if (temp1 != null && temp2 != null )
            {
                if (temp1.data != temp2.data )
                {
                    Console.WriteLine(temp1.data + " " + temp2.data);
                    return;
                }
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        Node root1 = newNode(5);
        root1.left = newNode(2);
        root1.right = newNode(7);
        root1.left.left = newNode(10);
        root1.left.right = newNode(11);
 
        Node root2 = newNode(6);
        root2.left = newNode(10);
        root2.right = newNode(15);
 
        findFirstUnmatch(root1,root2);
 
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript




<script>
 
// JavaScript program to find first leaves that are
// not same.
// Tree node
class Node
{
    constructor()
    {
        this.data = 0;
        this.left = null;
        this.right = null;
    }
}
// Utility method to create a new node
function newNode(x)
{
    var temp = new Node();
    temp.data = x;
    temp.left = null;
    temp.right = null;
    return temp;
}
function isLeaf(t)
{
    return ((t.left == null) && (t.right == null));
}
// Prints the first non-matching leaf node in
// two trees if it exists, else prints nothing.
function findFirstUnmatch(root1, root2)
{
    // If any of the tree is empty
    if (root1 == null || root2 == null)
    return;
    // Create two stacks for preorder traversals
    var s1 = [];
    var s2 = [];
    s1.push(root1);
    s2.push(root2);
    while (s1.length != 0 || s2.length != 0)
    {
        // If traversal of one tree is over
        // and other tree still has nodes.
        if (s1.length == 0 || s2.length == 0 )
        return;
        // Do iterative traversal of first tree
        // and find first lead node in it as "temp1"
        var temp1 = s1[s1.length-1];
        s1.pop();
        while (temp1 != null && isLeaf(temp1) != true)
        {
            // pushing right childfirst so that
            // left child comes first while popping.
            s1.push(temp1.right);
            s1.push(temp1.left);
            temp1 = s1[s1.length-1];
            s1.pop();
        }
        // Do iterative traversal of second tree
        // and find first lead node in it as "temp2"
        var temp2 = s2[s2.length-1];
        s2.pop();
        while (temp2 != null && isLeaf(temp2) != true)
        {
            s2.push(temp2.right);
            s2.push(temp2.left);
            temp2 = s2[s2.length-1];
            s2.pop();
        }
        // If we found leaves in both trees
        if (temp1 != null && temp2 != null )
        {
            if (temp1.data != temp2.data )
            {
                document.write("First non matching leaves : " +
                temp1.data + " " + temp2.data);
                return;
            }
        }
    }
}
// Driver code
var root1 = newNode(5);
root1.left = newNode(2);
root1.right = newNode(7);
root1.left.left = newNode(10);
root1.left.right = newNode(11);
var root2 = newNode(6);
root2.left = newNode(10);
root2.right = newNode(15);
findFirstUnmatch(root1,root2);
 
</script>


Output

First non matching leaves : 11  15

Time Complexity: O(n1+n2) where n1 and n2 are the total number of nodes in the two trees

Auxiliary Space: O(h1 + h2) where h1 and h2 are the heights of the two trees



Similar Reads

Tree with N nodes and K leaves such that distance between farthest leaves is minimized
Given N and K, print a tree such that the tree has no more than K leaf nodes and every other node has at least two nodes connected to it. The task is to build a tree of N nodes exactly in such a way that the distance between the farthest leaf nodes is minimized. Print the minimized distance also. Note: There can be multiple trees. Examples: Input:
6 min read
Minimum count of Full Binary Trees such that the count of leaves is N
Given an integer N and an infinite number of Full Binary Trees of different depths, the task is to choose minimum number of trees such that the sum of the count of leaf nodes in each of the tree is N.Example: Input: N = 7 Output: 3 Trees with depths 2, 1 and 0 can be picked with the number of leaf nodes as 4, 2 and 1 respectively. (4 + 2 + 1) = 7In
3 min read
Total number of possible Binary Search Trees and Binary Trees with n keys
Total number of possible Binary Search Trees with n different keys (countBST(n)) = Catalan number Cn = (2n)! / ((n + 1)! * n!) For n = 0, 1, 2, 3, … values of Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, .... So are numbers of Binary Search Trees. Total number of possible Binary Trees with n different keys (countBT(n)) = countBST(n
12 min read
Find the maximum path sum between two leaves of a binary tree
Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another. The maximum sum path may or may not go through the root. For example, in the following binary tree, the maximum sum is 27(3 + 6 + 9 + 0 - 1 + 10). Expected time complexity is O(n). If one side of the root is empty, then the
13 min read
Minimum sum path between two leaves of a binary tree
Given a binary tree in which each node element contains a number. The task is to find the minimum possible sum from one leaf node to another.If one side of root is empty, then function should return minus infinite.Examples: Input : 4 / \ 5 -6 / \ / \ 2 -3 1 8 Output : 1 The minimum sum path between two leaf nodes is: -3 -> 5 -> 4 -> -6 -
10 min read
Find sum of all left leaves in a given Binary Tree
Given a Binary Tree, find the sum of all left leaves in it. For example, sum of all left leaves in below Binary Tree is 5+1=6. Recommended PracticeSum of Left Leaf NodesTry It! The idea is to traverse the tree, starting from root. For every node, check if its left subtree is a leaf. If it is, then add it to the result. Following is the implementati
15+ min read
Find sum of all right leaves in a given Binary Tree
Given a Binary Tree, find sum of all right leaves in it. Similar article: Find sum of all left leaves in a given Binary Tree Example : Input : 1 / \ 2 3 / \ \ 4 5 8 \ / \ 2 6 7 Output : sum = 2 + 5 + 7 = 14Recommended PracticePaths from root with a specified sumTry It! Method 1: Recursive Method The idea is to traverse the tree starting from the ro
15+ min read
Construct a Maximum Binary Tree from two given Binary Trees
Given two Binary Trees, the task is to create a Maximum Binary Tree from the two given binary trees and print the Inorder Traversal of that tree. What is the maximum Binary Tree? The maximum binary is constructed in the following manner: In the case of both the Binary Trees having two corresponding nodes, the maximum of the two values is considered
8 min read
Height of binary tree considering even level leaves only
Find the height of the binary tree given that only the nodes on the even levels are considered valid leaf nodes. The height of a binary tree is the number of edges between the tree's root and its furthest leaf. But what if we bring a twist and change the definition of a leaf node? Let us define a valid leaf node as the node that has no children and
8 min read
Lowest Common Ancestor of the deepest leaves of a Binary Tree
Given a Binary Tree consisting of N nodes having distinct values from the range [1, N], the task is to find the lowest common ancestor of the deepest leaves of the binary tree. Examples: Input: Output: 1Explanation: The deepest leaf nodes of the tree are {8, 9, 10}. Lowest common ancestor of these nodes is 1. Input: Output: 6 Approach: The given pr
10 min read
Extract Leaves of a Binary Tree in a Doubly Linked List
Given a Binary Tree, extract all leaves of it in a Doubly Linked List (DLL). Note that the DLL need to be created in-place. Assume that the node structure of DLL and Binary Tree is same, only the meaning of left and right pointers are different. In DLL, left means previous pointer, and right means next pointer. Let the following be input binary tre
11 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 leaveRecommended PracticePrint Nodes having K leavesTry It! Here
7 min read
Find the Absolute Difference between the Right View Sum of two Binary Trees
Given two binary trees, the task is to find the sum of the absolute differences between the right view of binary trees. Examples: Input: Tree 1: 10 / \ 5 20 / \ \ 4 7 30 Tree 2: 50 / \ 25 60 / \ / \ 20 30 55 70 Output: 120Explanation: For Tree 1, the right view nodes are 10, 20, and 30. Therefore, the right view sum is 10 + 20 + 30 = 60, and For Tr
11 min read
Introduction to Generic Trees (N-ary Trees)
Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes. Every node stores address of its children and the very first node's address will be stored in a s
5 min read
Find product of sums of data of leaves at same levels | Set 2
Given a Binary Tree, return following value for it. For every level, compute sum of all leaves if there are leaves at this level. Otherwise ignore it.Return multiplication of all sums. Examples: Input: Root of below tree 2 / \ 7 5 \ 9 Output: 63 First levels doesn't have leaves. Second level has one leaf 7 and third level also has one leaf 9. There
9 min read
Find multiplication of sums of data of leaves at same levels
Given a Binary Tree, return following value for it. 1) For every level, compute sum of all leaves if there are leaves at this level. Otherwise, ignore it. 2) Return multiplication of all sums.Examples: Input: Root of below tree 2 / \ 7 5 \ 9Output: 63First levels doesn't have leaves. Second levelhas one leaf 7 and third level also has one leaf 9. T
15+ min read
Count the Number of Binary Search Trees present in a Binary Tree
Given a binary tree, the task is to count the number of Binary Search Trees present in it. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 4Here each leaf node represents a binary search tree and there are total 4 nodes. Input: 11 / \ 8 10 / / \ 5 9 8 / \ 4 6 Output: 6 Sub-tree rooted under node 5 is a BST 5 / \ 4 6 Another BST we have is rooted
10 min read
Iterative Approach to check if two Binary Trees are Isomorphic or not
Given two Binary Trees we have to detect if the two trees are Isomorphic. Two trees are called isomorphic if one of them can be obtained from another by a series of flips, i.e. by swapping left and right children of a number of nodes. Any number of nodes at any level can have their children swapped. Note: Two empty trees are isomorphic. For example
12 min read
Check if two binary trees are mirror | Set 3
Given two arrays, A[] and B[] consisting of M pairs, representing the edges of the two binary trees of N distinct nodes according to the level order traversal, the task is to check if trees are the mirror images of each other. Examples: Input: N = 6, M = 5, A[][2] = {{1, 5}, {1, 4}, {5, 7}, {5, 8}, {4, 9}}, B[][2] = {{1, 4}, {1, 5}, {4, 9}, {5, 8},
10 min read
Check if two Binary trees are identical after exactly K changes
Given two binary trees T1 and T2 and integer K, the task is to check whether both trees are identical or not after making exactly K changes in the first tree. In each change, one tree element can be converted into any other integer. Examples: Input: K = 1 T1 = 1 T2 = 1 / \ / \ 2 4 2 3Output: YesExplanation: Change the node with value 4 to value 3 I
9 min read
Merge Two Balanced Binary Search Trees
You are given two balanced binary search trees e.g., AVL or Red-Black Tree. Write a function that merges the two given balanced BSTs into a balanced binary search tree. Let there be m elements in the first tree and n elements in the other tree. Your merge function should take O(m+n) time.In the following solutions, it is assumed that the sizes of t
15+ min read
Print the elements of given two Binary Trees in sorted order
Given two binary trees, the task is to print the elements of both the binary trees in non-decreasing order. Examples: Input: Trees in the image below Output: 1 2 3 4 5 6Explanation: The nodes in the 1st and 2nd binary tree are {3, 1, 5} and {4, 2, 6} respectively. Upon merging and sorting the two arrays, the required array becomes {1, 2, 3, 4, 5, 6
15+ min read
Print Common Nodes in Two Binary Search Trees
Given two Binary Search Trees, find common nodes in them. In other words, find the intersection of two BSTs. Example: Input: root1: 5 / \ 1 10 / \ / 0 4 7 \ 9 root2: 10 / \ 7 20 / \4 9Output: 4 7 9 10 Recommended PracticeFind Common Nodes in two BSTsTry It! Naive Approach: A simple way is to one by one search every node of the first tree in the sec
15+ min read
Check if leaf traversal of two Binary Trees is same?
Leaf traversal is the sequence of leaves traversed from left to right. The problem is to check if the leaf traversals of two given Binary Trees are same or not.Expected time complexity O(n). Expected auxiliary space O(h1 + h2) where h1 and h2 are heights of two Binary Trees. Examples: Input: Roots of below Binary Trees 1 / \ 2 3 / / \ 4 6 7 0 / \ 5
15+ min read
Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
Given two binary trees. We need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the non-null node will be used as the node of new tree. Example: Input: Tree 1 Tree 2 2 3 / \ / \ 1 4 6 1 / \ \ 5 2 7 Output: Merged tree: 5 / \ 7 5 / \ \ 5 2 7 No
15+ min read
Largest number by which given 3 numbers should be divided such that they leaves same remainder
Given three numbers, our task is to find the largest number by which when given 3 numbers are divided leads to same remainder. It may be assumed that all given numbers are given in increasing order. Examples: Input : a = 62, b = 132, c = 237 Output : 35 35 leads to same remainder 27 when divides 62, 132 and 237. Input : a = 74, b = 272, c = 584 Out
9 min read
Generate Array whose sum of all K-size subarrays divided by N leaves remainder X
Given three integer N, K and X, the task is to create an array of length N such that sum of all its K-length subarrays modulo N is X.Examples: Input: N = 6, K = 3, X = 3 Output: 9 6 6 9 6 6 Explanation: All subarrays of length 3 and their respective sum%N values are as follows: [9, 6, 6] Sum = 21 % 6 = 3 [6, 6, 9] sum = 21 % 6 = 3 [6, 9, 6] sum = 2
4 min read
Minimum integer such that it leaves a remainder 1 on dividing with any element from the range [2, N]
Given an integer N, the task is to find the minimum possible integer X such that X % M = 1 for all M from the range [2, N]Examples: Input: N = 5 Output: 61 61 % 2 = 1 61 % 3 = 1 61 % 4 = 1 61 % 5 = 1Input: N = 2 Output: 3 Approach: Find the lcm of all the integers from the range [2, N] and store it in a variable lcm. Now we know that lcm is the sma
5 min read
Count of nodes which are at a distance X from root and leaves
Given two integers N and X, where N is the number of nodes in an almost complete binary tree. The task is to find: The number of nodes that are at X distance from the root.The number of nodes that are at X distance from any leaf in its subtree. Note: A Complete binary tree is a binary tree in which every level, except possibly the last, is complete
12 min read
Largest number less than or equal to Z that leaves a remainder X when divided by Y
Given three integers x, y, z, the task is to find the largest non-negative number less than or equal to z that leaves a remainder x when divided by y (Given x < y). If no such number exists then the output will be -1. Examples: Input: x = 1, y = 5, z = 8 Output: 6 Explanation: 6 is the largest number less than 8 which when divided by 5 leaves a
5 min read
Article Tags :
Practice Tags :