L114. Flatten Binary Tree to Linked List
recursion
Problem:
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
Solution:
make all left as null
public void flatten(TreeNode root) {
if(root == null) return;
TreeNode[] pre = new TreeNode[1];
helper(root, pre);
}
private void helper(TreeNode root, TreeNode[] pre){
if(root == null) return;
helper(root.right, pre);
helper(root.left, pre);
root.right = pre[0];
root.left = null;
pre[0] = root;
}
Last updated
Was this helpful?