Given a binary tree, flatten it to a linked list in-place.
For example,
Given
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
public class Solution { public void flatten(TreeNode root) { if(root == null){return;} TreeNode leftn = root.left; TreeNode rightn = root.right; flatten(leftn); flatten(rightn); root.left = null;//remove the left node root.right = leftn;(ex: 3) TreeNode cur = root;(ex: 2) while (cur.right != null) cur=cur.right; cur.right = rightn; (ex:3) (ex:4) } }
No comments:
Post a Comment