private TreeNode prev = null;
public void flatten(TreeNode root) {
if (root == null)
return;
flatten(root.right);
flatten(root.left);
root.right = prev;
root.left = null;
prev = root;
}
My short post order traversal Java solution for share

This is really brilliant! But flatten() would be unreusable if prev is set to a field. Here's another way of implementing the same idea.
public void flatten(TreeNode root) { flatten(root,null); } private TreeNode flatten(TreeNode root, TreeNode pre) { if(root==null) return pre; pre=flatten(root.right,pre); pre=flatten(root.left,pre); root.right=pre; root.left=null; pre=root; return pre; }

You go right first and I go left first. lol.
public class Solution { private static TreeNode pointer = null; public void flatten(TreeNode root) { if(root == null) return; if(pointer != null) pointer.right = root; pointer = root; TreeNode right = root.right; flatten(root.left); root.left = null; flatten(right); } }

So it is time to show my C++ Solution. 8ms From right to left.
class Solution { public: void flatten(TreeNode* root) { helper(root); } private: TreeNode* prev = NULL; void helper(TreeNode* root) { if (root == NULL) return; helper(root>right); helper(root>left); root>right = prev; root>left = NULL; prev = root; } };

//I also write an answer dealing the tree from left to right. class Solution { public: void flatten(TreeNode* root) { if (!root) return; helper(root); } private: void helper(TreeNode* root) { if (!root) return; if (!root>left && !root>right) return; else if (root>left == NULL && root>right != NULL) helper(root>right); else if (root>right == NULL && root>left != NULL) { helper(root>left); root>right = root>left; root>left = NULL; } else { helper(root>left); helper(root>right); TreeNode* p = root>right; root>right = root>left; root>left = NULL; TreeNode* q = root>right; while (q>right != NULL) q = q>right; q>right = p; } } };