Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 13, 2017 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/8b1020b558098539b3fd156523e0a2ea to your computer and use it in GitHub Desktop.
Save InterviewBytes/8b1020b558098539b3fd156523e0a2ea to your computer and use it in GitHub Desktop.
Flatten 1
package com.interviewbytes.trees;
import java.util.LinkedList;
import java.util.List;
public class Flatten1 {
public void flatten(TreeNode root) {
List<TreeNode> list = new LinkedList<>();
dfs(root, list);
TreeNode current = new TreeNode(0);
for (TreeNode n : list) {
current.right = n;
current.left = null;
current = current.right;
}
}
private void dfs(TreeNode node, List<TreeNode> list) {
if (node == null) return;
list.add(node);
dfs(node.left, list);
dfs(node.right, list);
}
}
package com.interviewbytes.trees;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment