Created
August 19, 2013 05:49
-
-
Save charlespunk/6266060 to your computer and use it in GitHub Desktop.
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
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 |
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
/** | |
* 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