Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active August 22, 2017 15:02
Show Gist options
  • Select an option

  • Save cixuuz/2a59c851a4f106fb5f985bac4d158dfb to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/2a59c851a4f106fb5f985bac4d158dfb to your computer and use it in GitHub Desktop.
[114. Flatten Binary Tree to Linked List] #leetcode
class Solution {
public void flatten(TreeNode root) {
while (root != null) {
TreeNode rightNode = root.right;
root.right = root.left;
root.left = null;
// find rightmost node
TreeNode node = root;
while (node.right != null) {
node = node.right;
}
node.right = rightNode;
// move to next right node
root = root.right;
}
}
}
// recursive
class Solution1 {
private TreeNode successor = null;
public void flatten(TreeNode root) {
if (root == null) return;
flatten(root.right);
flatten(root.left);
root.right = successor;
root.left = null;
successor = root;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment