VOOZH about

URL: https://www.geeksforgeeks.org/dsa/finding-minimum-steps-in-special-binary-tree/

⇱ Finding Minimum Steps in Special Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Finding Minimum Steps in Special Binary Tree

Last Updated : 8 Apr, 2024

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.


Output
1

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

Comment
Article Tags: