Created
May 30, 2015 08:03
-
-
Save charlespunk/2a39fff3abb202146500 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
/** | |
* Definition for a binary tree node. | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public void flatten(TreeNode root) { | |
flattenAndGetLast(root); | |
} | |
public TreeNode flattenAndGetLast(TreeNode root) { | |
if (root == null) { | |
return null; | |
} | |
TreeNode leftLast = flattenAndGetLast(root.left); | |
TreeNode rightLast = flattenAndGetLast(root.right); | |
if (leftLast != null) { | |
TreeNode oldRight = root.right; | |
root.right = root.left; | |
root.left = null; | |
leftLast.right = oldRight; | |
} | |
return rightLast == null ? (leftLast == null ? root : leftLast) : rightLast; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment