Open In App

Find the distance between given node and Last level

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Binary tree with an integer X, where X represents the node’s value in an integer. Find the distance between the given node and the last level of the subtree in which the given node lies. If X doesn’t lie return -1. 

Note: Every node’s value in the Binary tree will be unique.

Examples:

Input: {1, 2, 3, 4, 5, 6, 7, NULL, NULL, NULL, NULL, 8, 9, NULL, NULL, NULL, NULL, 10, 11}

x =3 

Output:  3
Explanation: Subtree of 3 

 

Input: {1, 2, 3, NULL, NULL, 5}

X = 5

Output: 0
Explanation: 5 is already at last level

 

Approach: This can be solved with the following idea:

Since node’s value is given which is integer. So if you want that node directly, you will need to search for it then store address. After searching problem becomes easy to understand. Now you can treat the stored node’s address as your root node. Then just recursively call over left part and right subpart then ask them to bring distance of them till last level node. Out of which take max because that will only the last level for your root node. 

Steps involved in the implementation of code:

  • First, take X and search it in Tree using the standard search algorithm in binary trees.
  • Now it can happen that node doesn’t exist. If not exist return -1 from here itself.
  • Otherwise, Treat this node’s address as your root node.
  • Call over the left subtree and ask to bring the distance of it to the last level node.
  • Call over the right subtree and ask to bring the distance of it to the last level node.
  • Out of 2 distances take out the maximum distance and add 1 to it.
  • Return that distance.

Below is the implementation of the above code:

C++




// C++ code for the above approach
#include <iostream>
#include <limits.h>
using namespace std;
 
// Creating Tree Structure
class TreeNode {
public:
    int val;
    TreeNode* left;
    TreeNode* right;
 
    TreeNode(int data)
    {
        val = data;
        left = NULL;
        right = NULL;
    }
};
 
// Search for X in Tree
TreeNode* search(TreeNode* root, int x)
{
 
    if (root == NULL)
        return NULL;
 
    if (root->val == x)
        return root;
 
    TreeNode* leftsubtree = search(root->left, x);
    if (leftsubtree != NULL)
        return leftsubtree;
 
    TreeNode* rightsubtree = search(root->right, x);
    return rightsubtree;
}
 
// Calculate distance between
// X and last level
int distance(TreeNode* root)
{
 
    if (root == NULL)
        return INT_MIN - 1;
 
    if (root->left == NULL && root->right == NULL)
        return 0;
 
    int leftAns = distance(root->left);
    int rightAns = distance(root->right);
 
    return max(leftAns, rightAns) + 1;
}
 
// Function to calculate distance between
// X and last Level
int DistanceTillLL(TreeNode* root, int x)
{
 
    // Search for X
    TreeNode* node = search(root, x);
 
    // If not found
    if (node == NULL)
        return -1;
 
    root = node;
    return distance(root);
}
 
// Driver code
int main()
{
    int x = 3;
    TreeNode* root = new TreeNode(1);
    root->left = new TreeNode(2);
    root->right = new TreeNode(3);
    root->left->left = new TreeNode(4);
    root->left->right = new TreeNode(5);
    root->right->right = new TreeNode(7);
    root->right->left = new TreeNode(6);
    root->right->left->left = new TreeNode(8);
    root->right->left->right = new TreeNode(9);
    root->right->left->right->left = new TreeNode(10);
    root->right->left->right->right = new TreeNode(11);
 
    // Function call
    cout << DistanceTillLL(root, x);
    return 0;
}


Java




// Java code for the above approach
import java.util.*;
 
// Creating Tree Structure
class TreeNode {
    int val;
    TreeNode left, right;
 
    TreeNode(int data)
    {
        val = data;
        left = null;
        right = null;
    }
}
 
class GFG {
 
    // Search for X in Tree
    static TreeNode search(TreeNode root, int x)
    {
        if (root == null)
            return null;
 
        if (root.val == x)
            return root;
 
        TreeNode leftsubtree = search(root.left, x);
        if (leftsubtree != null)
            return leftsubtree;
 
        TreeNode rightsubtree = search(root.right, x);
        return rightsubtree;
    }
 
    // Calculate distance between
    // X and last level
    static int distance(TreeNode root)
    {
        if (root == null)
            return Integer.MIN_VALUE + 1;
 
        if (root.left == null && root.right == null)
            return 0;
 
        int leftAns = distance(root.left);
        int rightAns = distance(root.right);
 
        return Math.max(leftAns, rightAns) + 1;
    }
 
    // Function to calculate distance between
    // X and last Level
    static int DistanceTillLL(TreeNode root, int x)
    {
        // Search for X
        TreeNode node = search(root, x);
 
        // If not found
        if (node == null)
            return -1;
 
        root = node;
        return distance(root);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int x = 3;
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(7);
        root.right.left = new TreeNode(6);
        root.right.left.left = new TreeNode(8);
        root.right.left.right = new TreeNode(9);
        root.right.left.right.left = new TreeNode(10);
        root.right.left.right.right = new TreeNode(11);
 
        // Function call
        System.out.println(DistanceTillLL(root, x));
    }
}
 
// This code is contributed by prasad264


Python




import sys
 
# Creating Tree Structure
class TreeNode:
    def __init__(self, data):
        self.val = data
        self.left = None
        self.right = None
 
# Search for X in Tree
def search(root, x):
 
    if root is None:
        return None
 
    if root.val == x:
        return root
 
    leftsubtree = search(root.left, x)
    if leftsubtree is not None:
        return leftsubtree
 
    rightsubtree = search(root.right, x)
    return rightsubtree
 
# Calculate distance between X and last level
def distance(root):
 
    if root is None:
        return -sys.maxsize - 1
 
    if root.left is None and root.right is None:
        return 0
 
    leftAns = distance(root.left)
    rightAns = distance(root.right)
 
    return max(leftAns, rightAns) + 1
 
# Function to calculate distance between X and last Level
def DistanceTillLL(root, x):
 
    # Search for X
    node = search(root, x)
 
    # If not found
    if node is None:
        return -1
 
    root = node
    return distance(root)
 
# Driver code
if __name__ == '__main__':
    x = 3
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.right = TreeNode(3)
    root.left.left = TreeNode(4)
    root.left.right = TreeNode(5)
    root.right.right = TreeNode(7)
    root.right.left = TreeNode(6)
    root.right.left.left = TreeNode(8)
    root.right.left.right = TreeNode(9)
    root.right.left.right.left = TreeNode(10)
    root.right.left.right.right = TreeNode(11)
 
    # Function call
    print(DistanceTillLL(root, x))


Javascript




// Creating Tree Structure
class TreeNode {
constructor(data) {
this.val = data;
this.left = null;
this.right = null;
}
}
 
// Search for X in Tree
function search(root, x) {
if (root === null) {
return null;
}
 
if (root.val === x) {
return root;
}
 
let leftsubtree = search(root.left, x);
if (leftsubtree !== null) {
return leftsubtree;
}
 
let rightsubtree = search(root.right, x);
return rightsubtree;
}
 
// Calculate distance between X and last level
function distance(root) {
if (root === null) {
return -Infinity;
}
 
if (root.left === null && root.right === null) {
return 0;
}
 
let leftAns = distance(root.left);
let rightAns = distance(root.right);
 
return Math.max(leftAns, rightAns) + 1;
}
 
// Function to calculate distance between X and last level
function DistanceTillLL(root, x) {
// Search for X
let node = search(root, x);
 
// If not found
if (node === null) {
return -1;
}
 
root = node;
return distance(root);
}
 
// Driver code
let x = 3;
let root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(7);
root.right.left = new TreeNode(6);
root.right.left.left = new TreeNode(8);
root.right.left.right = new TreeNode(9);
root.right.left.right.left = new TreeNode(10);
root.right.left.right.right = new TreeNode(11);
 
// Function call
console.log(DistanceTillLL(root, x));


C#




using System;
 
// Creating Tree Structure
public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
 
    public TreeNode(int data)
    {
        val = data;
        left = null;
        right = null;
    }
}
 
public class Program {
    // Search for X in Tree
    public static TreeNode Search(TreeNode root, int x)
    {
 
        if (root == null)
            return null;
 
        if (root.val == x)
            return root;
 
        TreeNode leftsubtree = Search(root.left, x);
        if (leftsubtree != null)
            return leftsubtree;
 
        TreeNode rightsubtree = Search(root.right, x);
        return rightsubtree;
    }
 
    // Calculate distance between
    // X and last level
    public static int Distance(TreeNode root)
    {
 
        if (root == null)
            return int.MinValue + 1;
 
        if (root.left == null && root.right == null)
            return 0;
 
        int leftAns = Distance(root.left);
        int rightAns = Distance(root.right);
 
        return Math.Max(leftAns, rightAns) + 1;
    }
 
    // Function to calculate distance between
    // X and last Level
    public static int DistanceTillLL(TreeNode root, int x)
    {
 
        // Search for X
        TreeNode node = Search(root, x);
 
        // If not found
        if (node == null)
            return -1;
 
        root = node;
        return Distance(root);
    }
 
    // Driver code
    public static void Main()
    {
        int x = 3;
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(7);
        root.right.left = new TreeNode(6);
        root.right.left.left = new TreeNode(8);
        root.right.left.right = new TreeNode(9);
        root.right.left.right.left = new TreeNode(10);
        root.right.left.right.right = new TreeNode(11);
 
        // Function call
        Console.WriteLine(DistanceTillLL(root, x));
    }
}


Output

3

Time Complexity : O(N) 
Auxiliary Space: O(h)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads