Created
November 24, 2018 16:06
-
-
Save wszdwp/b789c65c2bc3bb53124b0c912d2de759 to your computer and use it in GitHub Desktop.
binary tree to undirected graph
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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