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 \ 6
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
public class Solution {
public void flatten(TreeNode root) {
if(root == null) return ;
Stack<TreeNode> stack=new Stack<TreeNode>();
TreeNode p = root;
stack.add(p);
while (!stack.isEmpty()) {
p = stack.pop();
if(p.right != null)
stack.push(p.right);
if(p.left != null)
stack.push(p.left);
if(p.left==null&&p.right==null){
if(!stack.isEmpty())
p.left=stack.peek();
}
}
p = root;
while(p!=null){
System.out.println(p.val);
p=p.left;
}
while(p!=null){
if(p.left!=null) p.right=p.left;
p.left=null;
p=p.right;
}
}
}