Given a binary tree, flatten it to a linked list in-place.
For example,
Given
Given
1 / \ 2 5 / \ \ 3 4 6
1 \ 2 \ 3 \ 4 \ 5 \ 6Solution 1: Pre-order DFS
public class Solution {
TreeNode pre=null;
public void flatten(TreeNode root) {
if (root==null) return;
TreeNode left=root.left;//x can be change, record the left and right
TreeNode right=root.right;
if (pre!=null) {
pre.left=null;
pre.right=root;
}
pre=root;
flatten(left);
flatten(right);
}
}
Solution 2: Pre-order DFS, iterative
public class Solution {
public void flatten(TreeNode root) {
Deque<TreeNode> stack=new LinkedList<>();
Queue<TreeNode> qu=new LinkedList<>();
TreeNode x=root;
while (x!=null || !stack.isEmpty()) {
if (x!=null) {
stack.push(x);
qu.offer(x);
x=x.left;
}
else {
x=stack.pop();
x=x.right;
}
}
while (!qu.isEmpty()) {
x=qu.poll();
x.left=null;
x.right=qu.isEmpty()?null:qu.peek();
}
}
}
没有评论:
发表评论