Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlespunk/2a39fff3abb202146500 to your computer and use it in GitHub Desktop.
Save charlespunk/2a39fff3abb202146500 to your computer and use it in GitHub Desktop.
/**
* 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