Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Created November 24, 2018 16:06
Show Gist options
  • Select an option

  • Save wszdwp/b789c65c2bc3bb53124b0c912d2de759 to your computer and use it in GitHub Desktop.

Select an option

Save wszdwp/b789c65c2bc3bb53124b0c912d2de759 to your computer and use it in GitHub Desktop.
binary tree to undirected graph
// binary tree to undirected graph
// treeToGraph(null, root);
public void treeToGraph(TreeNode parent, TreeNode child) {
if (parent != null) {
List<TreeNode> pNeighbors = g.getOrDefault(parent, new ArrayList<TreeNode>());
pNeighbors.add(child);
g.put(parent, pNeighbors);
List<TreeNode> cNeighbors = g.getOrDefault(child, new ArrayList<TreeNode>());
cNeighbors.add(parent);
g.put(child, cNeighbors);
}
if (child.left != null) treeToGraph(child, child.left);
if (child.right != null) treeToGraph(child, child.right);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment