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:
Find Minimum Depth of a Binary Tree
Next article icon

Finding Minimum Steps in Special Binary Tree

Last Updated : 08 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two integer values (i and j) as input representing two nodes of a special binary tree. The special binary tree has this property that the root node's value is always 1 and for every node, its left child will be the node's value * 3, and the right child will be ( node's value * 3) + 1. The given integer values exist in the tree then find the minimum steps required to reach the other node. By moving one step you can either move one level up or go one level down.

Examples:

Input: i = 1, j = 3
Output: 1
Explanation: The tree for the above input will be

1
/ \
3 4

The difference between levels of 1 and 3 is 1 so it will take 1 step.

Input: i = 1, j = 39
Output: 3
Explanation: The tree for the above input will be

1
/ \
3 4
/ \ / \
9 10 12 13
/ \ / \ / \ / \
27 28 30 31 36 37 38 39

Here the difference between level of 1 and 39 is 3 so it will take 3 steps.

Intuition: To solve the problem follow the below idea:

Start generating the tree with the mentioned property until we encounter both the nodes and as soon as we found both the nodes then find level of both nodes and return absolute difference between them.

Approach: Follow the below steps:

We will use a 2D Vector for constructing the binary tree and the row of 2D vector will represent level of current row so it will be easy for further calculation. Initialize three variables ithRow = -1 , jthRow = -1 and row = 0, along with a 2D vector arr with value 1. Now run a while loop till ithRow == - 1 and jthRow == -1 and repeat the below mentioned steps for every iteration. NOTE: i and j are input values.

  • Run a while loop till row<i or row<j and initialize a vector temp.
  • Now iterate over the previous row of 2D vector arr using a for loop and calculate child's values using the formula mentioned in question.
  • If child1's or child2's value matches input value then update respective row tracking variables i.e. ithRow and jthRow .
  • After this push child1 and child2 in temp vector then push temp vector in 2D vector arr and increment row count.
  • Then check whether we have found both the values if yes then break the loop.
  • At last return the absolute difference between ithRow and jthRow.

Below Code is the implementation of above approach in CPP.

C++
// C++ code for the above approach: #include <bits/stdc++.h> using namespace std; int findMinimumSteps(int i, int j) {      // Two variables for tracking level of     // input variables and row for maintaining     // row details     int ithRow = -1, jthRow = -1, row = 0;      // 2D vector to create tree     vector<vector<int> > arr;     arr.push_back({ 1 });     while (ithRow == -1 && jthRow == -1) {         while (row < i || row < j) {              // Variable for storing             // children of previous row             vector<int> temp;             for (int k = 0; k < arr[row].size(); k++) {                 // Calculating child's values as                 // given in question                 int child1 = arr[row][i] * 3;                 int child2 = (arr[row][i] * 3) + 1;                  // Checking whether any child's                 // value matches given input if                 // yes then update respective                 // row tracker                 if (child1 == i)                     ithRow = row + 1;                 if (child2 == i)                     ithRow = row + 1;                 if (child1 == j)                     jthRow = row + 1;                 if (child2 == j)                     jthRow = row + 1;                  // Pushing both childs into vector                 temp.push_back(child1);                 temp.push_back(child2);             }              // Insert new row so count             // will be increased             row++;              // push the calculated             // childs in the 2D vector             arr.push_back(temp);              // if both values are found then             // break the loop             if (ithRow != -1 && jthRow != -1)                 break;         }     }      // Returning the absolute     // difference between the level of     // given two input nodes     return abs(ithRow - jthRow); }  // Drivers code int main() {     int i = 1;     int j = 3;      // Function call     cout << findMinimumSteps(i, j);     return 0; } 
Java
import java.util.ArrayList; import java.util.List;  public class MinimumSteps {      static int findMinimumSteps(int i, int j) {         int ithRow = -1, jthRow = -1, row = 0;          // 2D list to create a tree         List<List<Integer>> arr = new ArrayList<>();         arr.add(List.of(1));          while (ithRow == -1 && jthRow == -1) {             while (row < i || row < j) {                 // List for storing children of the previous row                 List<Integer> temp = new ArrayList<>();                  for (int k = 0; k < arr.get(row).size(); k++) {                     // Calculating child's values as given in the question                     int child1 = arr.get(row).get(k) * 3;                     int child2 = arr.get(row).get(k) * 3 + 1;                      // Checking whether any child's value matches the given input                     // If yes, then update the respective row tracker                     if (child1 == i) ithRow = row + 1;                     if (child2 == i) ithRow = row + 1;                     if (child1 == j) jthRow = row + 1;                     if (child2 == j) jthRow = row + 1;                      // Pushing both children into the list                     temp.add(child1);                     temp.add(child2);                 }                  // Inserting a new row so the count will be increased                 row++;                  // Pushing the calculated children into the 2D list                 arr.add(new ArrayList<>(temp));                  // If both values are found, then break the loop                 if (ithRow != -1 && jthRow != -1) break;             }         }          // Returning the absolute difference between the levels of the given two input nodes         return Math.abs(ithRow - jthRow)-1;     }      // Driver code     public static void main(String[] args) {         int i = 1;         int j = 3;          // Function call         System.out.println(findMinimumSteps(i, j));     } } 
Python3
def find_minimum_steps(i, j):     # Function to calculate the level of a given node in the tree     def calculate_level(node):         level = 0         while node > 1:             if node % 3 == 0:                 node //= 3             else:                 node = (node - 1) // 3             level += 1         return level      # Calculate levels for both input nodes     ith_level = calculate_level(i)     jth_level = calculate_level(j)      # Return the absolute difference between the levels     return abs(ith_level - jth_level)  if __name__ == "__main__":     i = 1     j = 3      # Function call     print(find_minimum_steps(i, j)) 
C#
using System; using System.Collections.Generic;  class Program {     // Function to find the minimum steps between two nodes in a tree     static int FindMinimumSteps(int i, int j)     {         // Variables to track the level of input nodes         int ithRow = -1, jthRow = -1, row = 0;          // 2D list to represent the tree         List<List<int>> arr = new List<List<int>>();         arr.Add(new List<int> { 1 }); // Initial row with root node value 1          // Continue until both nodes are found in the tree         while (ithRow == -1 && jthRow == -1)         {             // Process each node in the current row             while (row < i || row < j)             {                 List<int> temp = new List<int>();                 for (int k = 0; k < arr[row].Count; k++)                 {                     // Calculate children values based on the given formula                     int child1 = arr[row][k] * 3;                     int child2 = (arr[row][k] * 3) + 1;                      // Check if any child's value matches the input nodes                     if (child1 == i)                         ithRow = row + 1;                     if (child2 == i)                         ithRow = row + 1;                     if (child1 == j)                         jthRow = row + 1;                     if (child2 == j)                         jthRow = row + 1;                      // Add both children to the temporary list                     temp.Add(child1);                     temp.Add(child2);                 }                  // Move to the next row                 row++;                  // Add the calculated children to the 2D list                 arr.Add(new List<int>(temp));                  // If both values are found, break the loop                 if (ithRow != -1 && jthRow != -1)                     break;             }         }          // Return the absolute difference between the levels of the two input nodes         return Math.Abs(ithRow - jthRow + 1) ;     }      // Main method to test the FindMinimumSteps function     static void Main()     {         int i = 1;         int j = 3;          // Call the function and print the result         Console.WriteLine(FindMinimumSteps(i, j));     } } 
JavaScript
function findMinimumSteps(i, j) {     let ithRow = -1, jthRow = -1, row = 0;      // 2D array to create a tree     let arr = [[]];     arr[0] = [1];      while (ithRow === -1 && jthRow === -1) {         while (row < i || row < j) {             // Array for storing children of the previous row             let temp = [];              for (let k = 0; k < arr[row].length; k++) {                 // Calculating child's values as given in the question                 let child1 = arr[row][k] * 3;                 let child2 = arr[row][k] * 3 + 1;                  // Checking whether any child's value matches the given input                 // If yes, then update the respective row tracker                 if (child1 === i) ithRow = row + 1;                 if (child2 === i) ithRow = row + 1;                 if (child1 === j) jthRow = row + 1;                 if (child2 === j) jthRow = row + 1;                  // Pushing both children into the array                 temp.push(child1);                 temp.push(child2);             }              // Inserting a new row so the count will be increased             row++;              // Pushing the calculated children into the 2D array             arr.push([...temp]);              // If both values are found, then break the loop             if (ithRow !== -1 && jthRow !== -1) break;         }     }      // Returning the absolute difference between the levels of the given two input nodes     return Math.abs(ithRow - jthRow) - 1; }  // Driver code let i = 1; let j = 3;  // Function call console.log(findMinimumSteps(i, j)); 

Output
1

Time Complexity: O(i*j)
Auxiliary Space: O((max(i, j)/3)^2)


Next Article
Find Minimum Depth of a Binary Tree

N

nichil942singh
Improve
Article Tags :
  • Tree
  • DSA
  • Data Structures-Binary Trees
Practice Tags :
  • Tree

Similar Reads

  • Find a number in minimum steps
    Given an infinite number line from -INFINITY to +INFINITY and we are on zero. We can move n steps either side at each n'th time. Approach 1 : Using Tree 1st time; we can move only 1 step to both ways, means -1 1; 2nd time we can move 2 steps from -1 and 1; -1 : -3 (-1-2) 1(-1+2) 1 : -1 ( 1-2) 3(1+2)
    15 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: Output: 2Explanation: The right view of the given binary
    8 min read
  • Find Minimum Depth of a Binary Tree
    Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, minimum depth of below Binary Tree is 2. Note that the path must end on a leaf node. For example, the minimum depth of below Bi
    15 min read
  • Find the largest Perfect Subtree in a given Binary Tree
    Given a Binary Tree, the task is to find the size of largest Perfect sub-tree in the given Binary Tree. Perfect Binary Tree - A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are at the same level. Examples: Input: 1 / \ 2 3 / \ / 4 5 6 Output: Size :
    12 min read
  • Find number of path with same moves in full Binary Tree
    Consider a Binary Tree having N nodes having root equal to 1. In which for any node X, the left and right child are 2*X and ((2*X) + 1). Then in such a Binary Tree, there can be four possible moves: From parent node to left child node (Let us name this move as BL, which means Bottom Left)From parent
    15+ min read
  • Insertion in Binary Search Tree (BST)
    Given a BST, the task is to insert a new node in this BST. Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is f
    15+ min read
  • Find the closest leaf in a Binary Tree
    Given a Binary Tree and a key 'k', find distance of the closest leaf from 'k'. Examples: A / \ B C / \ E F / \ G H / \ / I J K Closest leaf to 'H' is 'K', so distance is 1 for 'H' Closest leaf to 'C' is 'B', so distance is 2 for 'C' Closest leaf to 'E' is either 'I' or 'J', so distance is 2 for 'E'
    14 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 a
    15+ min read
  • Find n-th node in Preorder traversal of a Binary Tree
    Given a binary tree. The task is to find the n-th node of preorder traversal. Examples: Input: Output: 50Explanation: Preorder Traversal is: 10 20 40 50 30 and value of 4th node is 50.Input: Output : 3Explanation: Preorder Traversal is: 7 2 3 8 5 and value of 3rd node is 3. Table of Content [Naive A
    11 min read
  • Count of Fibonacci paths in a Binary tree
    Given a Binary Tree, the task is to count the number of Fibonacci paths in the given Binary Tree. Fibonacci Path is a path which contains all nodes in root to leaf path are terms of Fibonacci series. Example: Input: 0 / \ 1 1 / \ / \ 1 10 70 1 / \ 81 2 Output: 2 Explanation: There are 2 Fibonacci pa
    10 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