Created
March 3, 2019 16:29
-
-
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
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
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