This is one approach that might not be the best and optimal solution in terms of memory.
So suggestions/ improvements are welcome.
Algorithm-
- Traverse BT using a Breadth-First Search (Level order) approach.
- While traversing, consider blank spaces(where node isn’t present) as ‘-1’
- Insert BFS path elements in an array Find indices of 2 node elements to be found.
- Calculate distance using indexes.
Complexity-
Time: O(N)
Space: O(N)
Assumptions-
Every node in BT has a unique value.
class Node {
Node() {
value = -1;
}
Node(int num) {
value = num;
}
int value;
Node left = null;
Node right = null;
}
Declaring some required DS
static Queue<Node> queue = new LinkedList<Node>();
static ArrayList<Integer> list = new ArrayList<Integer>();
static Set<Integer> set = new HashSet<Integer>();
Then three functions
static void convertBTToArray() {
if (set.isEmpty())
return;
Node node = queue.poll();
if (node != null) {
list.add(node.value);
if (node.value != -1)
set.remove(node.value);
if (node.left != null) {
queue.add(node.left);
set.add(node.left.value);
} else
queue.add(new Node());
if (node.right != null) {
queue.add(node.right);
set.add(node.right.value);
} else
queue.add(new Node());
convertBTToArray();
} else
return;
}
static void init(Node root) {
// traverse in BFS fashion (level order) and convert to Array.
Node rootCopy = root;
if (rootCopy != null) {
queue.add(rootCopy);
set.add(rootCopy.value);
convertBTToArray();
}
}
// get distance between start and end values.
static int getHorizontalDistance(int startValue, int endValue) {
int startIndex = -1, endIndex = -1;
for (int i = 0; i < list.size(); i++) {
if (startIndex == -1)
startIndex = list.get(i) == startValue ? i : -1;
if (list.get(i) == endValue) {
endIndex = i;
break;
}
}
// check if both numbers are from same level else return -1
if (Math.floor(Math.log(startIndex + 1) / Math.log(2)) >= 0
&& Math.floor(Math.log(endIndex + 1) / Math.log(2)) >= 0)
return (endIndex - startIndex - 1);
else
return -1;
}
and finally the main method
public static void main(String...s) {
// create your tree and enter elements here
// -1 indicates that distance cant be found and hence invalid input.
System.out.println("Dist(7,1): "+getHorizontalDistance(7, 1));
}
4
, he calculated the number of steps froma
tod
by goinga->g->f->h->d
or a total of4
steps away. – Buckra