Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6Solution 1
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;
}
Solution 2
//straight forward
public void flatten2(TreeNode root) {
if (root == null) return;
TreeNode left = root.left;
TreeNode right = root.right;
root.left = null;
flatten(left);
flatten(right);
root.right = left;
TreeNode cur = root;
while (cur.right != null) cur = cur.right;
cur.right = right;
}
Solution 3 DFS stack
//DFS Use a stack
public void flatten3(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode curr = stack.pop();
if (curr.right!=null)
stack.push(curr.right);
if (curr.left!=null)
stack.push(curr.left);
if (!stack.isEmpty())
curr.right = stack.peek();
curr.left = null; // dont forget this!!
}
}