# Clean straight forward postorder solution! Easy to understand!

• I came up with another postorder solution, the idea is simple:
(1) flatten left subtree, return its tail node 'leftTail'
(2) flatten right subtree, return its tail node 'rightTail'
(3) if left subtree exists and has been flattened, we need to move it to the right:
set flattened right subtree as leftTail.right
set flattened left subtree to be the new right subtree(root.right)
set root.left=null
(4) return the tail node of this flattened tree (return rightTail if it isn't null, else return leftTail if it isn't null, else return root)

I change the return type in order to keep only one recursive fuction, it works for leetcode:)

``````public TreeNode flatten(TreeNode root) {
if(root==null) return null;
TreeNode leftTail = flatten(root.left);
TreeNode rightTail = flatten(root.right);
if(root.left!=null) {
leftTail.right = root.right;
root.right=root.left;
root.left=null;
}
return rightTail!=null?rightTail:(leftTail!=null?leftTail:root);
}``````

• @tongzhou2 I guess this is postorder traversal, not preorder.

• @jeantimex Hey thanks for your reply, hmm I agree with u!
BTW haven't seen your in leetcode for a while, how is it going?

• @tongzhou2 Been busy on my open source projects, in the meantime, trying to solve leetcode problems using JavaScript. I like your solution!

• @jeantimex Oh man that's awesome!

• Easy to understand. Should be upvoted

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