private TreeNode flattenHelper(TreeNode root) {
        if (root == null) return null;
        TreeNode leftTail = flattenHelper(root.left);
        TreeNode rightTail = flattenHelper(root.right);
        if (leftTail != null) {
            leftTail.right = root.right;
            root.right = root.left;
            root.left = null;
        }

        if (rightTail != null) return rightTail;
        else if (leftTail != null) return leftTail;
        else return root;
    }