I have the following piecewise continuous function:
$$f(x)=\begin{cases}3x+1,~x\gt 0\\2-x^2,~x\leq 0\end{cases}$$
and I need to find its right inverse.
Thus far I got that
$$g(x)=\begin{cases}\dfrac{x-1}{3},~x\gt 1\\ \\ \sqrt{2-x},~x\leq 2\end{cases}$$
but what can I do when I have an intersection? For example, if $x = 2$, along which branch will it go?
Therefore, I write my inverse function like this:
$$g(x)=\begin{cases}\dfrac{x-1}{3},~x\gt 1\\ \\ \sqrt{2-x},~x\leq 1\end{cases}$$
Is this approach and final function valid?
Note: OPs approach is almost correct. The details below should help to clarify open aspects.
Let's have a look at some aspects of the function $f:\mathbb{R}\rightarrow \mathbb{R}$ with \begin{align*} f(x)=\begin{cases} 3x+1&~x> 0\\ 2-x^2&~x\leq 0 \end{cases}\tag{1} \end{align*}
We have added the domain $\mathbb{R}$ and codomain $\mathbb{R}$ in order to fully specify the function $f$. This can be crucial for determination of a right inverse function, as we will see in a note at the end of the answer.
We see that e.g. $f(0)=2=f(\frac{1}{3})$. In $f((-1,\frac{1}{3}])$ there is more than one candidate for a right inverse function $g$.
Since \begin{align*} \lim_{x\rightarrow 0^+}f(x)&=\lim_{x\rightarrow 0^+}(3x+1)=1\\ \lim_{x\rightarrow 0^-}f(x)&=\lim_{x\rightarrow 0^-}(2-x^2)=2\\ \\ f(0)&=2-0^2=2\\ \end{align*} we see that the left-hand limit at $x=0$ is equal to $f(0)=2$ while the right-hand limit at $x=0$ is different. So $f$ is not continuous at $0$.
We take in (3) the negative square root $-\sqrt{2-x}$. This implies that $g(x)=-\sqrt{2-x}\leq 0$ and we can use the branch $f(x)=2-x^2$.
Note: It's relevant to specify domain and codomain of a function to determine a right inverse function for it. Consider the functions \begin{align*} &u:\mathbb{R}\rightarrow\mathbb{R}\qquad&v:\mathbb{R}\rightarrow[0,\infty)\\ &u(x)=x^2&v(x)=x^2 \end{align*} We see that $u(x)=v(x)=x^2$, but $u$ is not surjective as opposed to $v$. Therefore $v$ has a right inverse and $u$ has no right inverse.