Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlespunk/6266060 to your computer and use it in GitHub Desktop.
Save charlespunk/6266060 to your computer and use it in GitHub Desktop.
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root == null) return;
flattenRecurse(root);
}
public TreeNode flattenRecurse(TreeNode root){
if(root.left == null && root.right == null) return root;
else if(root.left != null && root.right != null){
TreeNode right = root.right;
TreeNode leftEnd = flattenRecurse(root.left);
root.right = root.left;
leftEnd.right = right;
root.left = null;
return flattenRecurse(right);
}
else{
root.right = root.right == null? root.left: root.right;
root.left = null;
return flattenRecurse(root.right);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment