Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes InterviewBytes/Flatten1.java Secret
Created Jun 13, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.