114. Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
class Solution {
public void flatten(TreeNode root) {
TreeNode curNode = root, preNode = root;
while (curNode != null) {
if (curNode.left == null) {
curNode = curNode.right;
}
else {
preNode = curNode.left;
while (preNode.right != null) {
preNode = preNode.right;
}
preNode.right = curNode.right;
curNode.right = curNode.left;
curNode.left = null;
curNode = curNode.right;
}
}
}
}
public void flatten(TreeNode root) {
if (root == null) {
return;
}
TreeNode rightSubTree = root.right;
root.right = root.left;
root.left = null;
TreeNode curNode = root;
while (curNode.right != null) {
curNode = curNode.right;
}
curNode.right = rightSubTree;
flatten(root.right);
}
class Solution {
public void flatten(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode curNode = stack.pop();
if (curNode.right != null) {
stack.push(curNode.right);
}
if (curNode.left != null) {
stack.push(curNode.left);
}
if (!stack.isEmpty()) {
curNode.right = stack.peek();
}
curNode.left = null;
}
}
}
3. Time & Space Complexity