Difficulty:: Medium
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1 2 3 4 5
| 1 / \ 2 5 / \ \ 3 4 6
|
The flattened tree should look like:
1 2 3 4 5 6 7 8 9 10 11
| 1 \ 2 \ 3 \ 4 \ 5 \ 6
|
Solution
Language: Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
class Solution { public void flatten(TreeNode root) { helper(root); } private TreeNode[] helper(TreeNode root) { if (root == null) { return null; } if (root.left == null && root.right == null) { return new TreeNode[]{root, root}; } TreeNode[] leftRes = helper(root.left); TreeNode[] rightRes = helper(root.right); root.left = null; TreeNode right = root; if (leftRes != null) { right.right = leftRes[0]; right = leftRes[1]; right.right = null; } if (rightRes != null) { right.right = rightRes[0]; right = rightRes[1]; right.right = null; } return new TreeNode[] {root, right}; } }
|