Binary Trees Custom Tree

You are given 2 Strings of equal length.

  1. Let the strings be str1 and str2. Now, we have have a link between str1.charAt(i)

    and str2.charAt(i) such that str1.charAt(i) is the parent and str2.charAt(i) is the child.

  2. Keeping this relation in mind, you have to form a binary tree and print the contents.

Sample Input

aabcdczyx
bgcdefyxw

Sample Output

b <= a => g
c <= b => .
d <= c => f
e <= d => .
. <= e => .
. <= f => .
. <= g => .

y <= z => .
x <= y => .
w <= x => .
. <= w => .
class Solution {
    public void populateHelper(String s1, String s2, HashMap<Character, Node> map, HashMap<Character, Boolean> marker,
            int index) {
        if (index == s1.length())
            return;
        Node root = map.getOrDefault(s1.charAt(index), new Node(s1.charAt(index)));
        if (!marker.containsKey(s1.charAt(index)))
            marker.put(s1.charAt(index), true);
        Node child = map.getOrDefault(s2.charAt(index), new Node(s2.charAt(index)));
        marker.put(s2.charAt(index), false);
        if (root.left == null)
            root.left = child;
        else
            root.right = child;
        map.put(s1.charAt(index), root);
        map.put(s2.charAt(index), child);

        populateHelper(s1, s2, map, marker, index + 1);
    }

    public ArrayList<Node> populate(String str1, String str2) {
        HashMap<Character, Node> map = new HashMap<>();
        HashMap<Character, Boolean> marker = new HashMap<>();
        populateHelper(str1, str2, map, marker, 0);
        ArrayList<Node> ans = new ArrayList<>();
        for (char x : marker.keySet())
            if (marker.get(x))
                ans.add(map.get(x));
        return ans;
    }
}

Last updated