Skip to content

Instantly share code, notes, and snippets.

@tolinwei
Created October 29, 2021 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tolinwei/65a88e03ea5a8a81ea856d531f132524 to your computer and use it in GitHub Desktop.
Save tolinwei/65a88e03ea5a8a81ea856d531f132524 to your computer and use it in GitHub Desktop.
Flatten BinaryTree
public void flatten(TreeNode root) {
while (root != null) {
if (root.left != null) {
// find the right most in left subtree
TreeNode rightMostInLeft = root.left;
while (rightMostInLeft.right != null) {
rightMostInLeft = rightMostInLeft.right;
}
rightMostInLeft.right = root.right;
root.right = root.left;
root.left = null;
}
root = root.right;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment