/**
* 114. Flatten Binary Tree to Linked List
* 1. Time:O(n) Space:O(logn)
* 2. Time:O(n) Space:O(1)
* 3. Time:O(n) Space:O(logn)
*/
// 1. Time:O(n) Space:O(logn)
class Solution {
public void flatten(TreeNode root) {
if(root==null) return;
flatten(root.left);
flatten(root.right);
if(root.left==null) return;
TreeNode tmp = root.left;
while(tmp.right!=null) tmp = tmp.right;
tmp.right = root.right;
root.right = root.left;
root.left = null;
}
}
// 2. Time:O(n) Space:O(1)
class Solution {
public void flatten(TreeNode root) {
TreeNode cur = root;
TreeNode prev = null;
while(cur!=null){
if(cur.left==null)
cur = cur.right;
else{
prev = cur.left;
while(prev.right!=null)
prev = prev.right;
prev.right = cur.right;
cur.right = cur.left;
cur.left = null;
}
}
}
}
// 3. Time:O(n) Space:O(logn)
class Solution {
private TreeNode prev = null;
public void flatten(TreeNode root) {
if(root==null) return;
flatten(root.right);
flatten(root.left);
root.right = prev;
root.left = null;
prev = root;
}
}