Posted

Reading Time: 1 minute

If we are given a binary tree (with the root node), we can build a tree map without generating extra edges by using this helper method:

  • it is an undirected graph with no weight/weight value of 1
  • the method of drawing is done using Depth First Search – DFS

Map<TreeNode, List<TreeNode>> graph = new HashMap<>();


buildTreeGraph(null, root);

private void buildTreeGraph(TreeNode parent, TreeNode child) {
if (parent != null) {
graph.computeIfAbsent(parent, x -> new ArrayList<>()).add(child);
graph.computeIfAbsent(child, x -> new ArrayList<>()).add(parent);
}

if (child.left != null) {
buildTreeGraph(child, child.left);
}
if (child.right != null) {
buildTreeGraph(child, child.right);
}
}

Notes:

  1. The method Map.computeIfAbsent(key, Function) computes the new value and associates it with the key if there is no mapping for the given key or the mapping is null.
    Also, it returns the new value associated with the key. If the mapping function will return null the value will not be put into the map.
  2. The TreeNode class is displayed below:

public class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}
}





Thanks for reading. I hope you learned something interesting about React!
If you found this article useful, please share it with others. Don’t forget to subscribe to get notified for the upcoming articles.