-
-
Save InterviewBytes/8b1020b558098539b3fd156523e0a2ea to your computer and use it in GitHub Desktop.
Flatten 1
This file contains 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
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); | |
} | |
} |
This file contains 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
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