Skip to content

Instantly share code, notes, and snippets.

@y0n1
Created March 3, 2019 16:29
Show Gist options
  • Save y0n1/d3d4cfafc6bf688a007bc9507435fe7a to your computer and use it in GitHub Desktop.
Save y0n1/d3d4cfafc6bf688a007bc9507435fe7a to your computer and use it in GitHub Desktop.
Flatten a binary tree in O(1) space and O(n) time complexity
public class Program {
internal class Node<T> {
final T data;
final Node<T> left;
final Node<T> right;
bool hasLeftChild() {
return this.left != null;
}
}
static void flattenTree(Node<int> root) {
Node<int> currentRoot = root;
Node<int> currentLeaf = root;
while (currentRoot.hasLeftChild()) {
while (currentLeaf.hasLeftChild()) {
currentLeaf = currentLeaf.left;
}
currentLeaf.left = currentRoot.right;
currentRoot.right = null;
currentRoot = currentRoot.left;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment