# Straightforward Java Solution

• ``````public void flatten(TreeNode root) {
if (root == null) return;

TreeNode left = root.left;
TreeNode right = root.right;

root.left = null;

flatten(left);
flatten(right);

root.right = left;
TreeNode cur = root;
while (cur.right != null) cur = cur.right;
cur.right = right;
}
``````

This solution is based on recursion. We simply flatten left and right subtree and paste each sublist to the right child of the root. (don't forget to set left child to null)

• recursion is a good way

• Great solution, thank you for sharing. I got the idea and then implemented it on my own.

• Good for you

• Pretty smart way to solve it. +1

• Clearest recursive solution I have ever seen

• Can someone tell me what is the time complecity of this solution?

• ``````public void Flatten(TreeNode root) {
solve(root, null);
}
TreeNode solve(TreeNode root, TreeNode last)    {
if(root == null) return last;
root.right = solve(root.left, solve(root.right, last));
root.left = null;
return root;
}``````

• same idea, i prefer this one than the top 1 post.

• This is not O(N) though.

• This post is deleted!

• I think the solution has complexity `O(nlogn)`

• Complexity is still O(n). You never visit a node more than twice if you think about it.

• Very straight forward and easy to understand. Thanks!

• Your code is so clear and easy to understand!

• similar idea

``````    public void flatten(TreeNode root) {
flatTree(root);
}

private TreeNode flatTree(TreeNode node) {
if (null == node) return null;

TreeNode rightTree = flatTree(node.right);  // 4-5-6
TreeNode leftTree = flatTree(node.left);    // 2-3-4
if (null != leftTree ) {
// append right to left.
TreeNode x = leftTree;
while (x.right != null) {
x = x.right;
}
x.right = rightTree;
node.right = leftTree;
}
else node.right = rightTree;

node.left = null;

return node;
}
``````

• @xiong6 Why the complexity is O(nlogn) ? Could you please explain it?

• @BetaGoGoGo Nope. It is o(n^2). Every time you traverse downward to the very end of the left branch end. Since the tree is serialized it will be O(n^2) no matter how balanced it originally was.

• @MrARang I think it is not o(nlog n). Please check my previous post. Please correct me if I made a mistake.

• @bxli127 Hi I think for a balanced tree the time is O(nlogn). let's say the balanced tree's height is 4, the 1st level counts 8 node visit, the 2nd level counts 4+4=8 , 3rd level 2+6, 4th level 1+7. so 8*4, 8 being the number of leaves and 4 the height. how do you think?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.